forge
Explore
Log in

Don't you dare go Hollow

Live runner config and server settings in admin UI

Browse files at this commit

8609bad307add05c95a3d5fb0378ff403ef6c791Ahmet Kaan GümüşParent: 63d7a81
  • feat
    • live runner config and server settings in admin UI
Show full message
✨ feat: live runner config and server settings in admin UI

- 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.rsmodified+61 -1
@@ -46,11 +46,31 @@ impl fmt::Debug for RegisterResponse {
46 46
47 /// `POST /api/v1/ci/runners/claim`. Long-polls for up to 30s; 204 means nothing was claimed.47 /// `POST /api/v1/ci/runners/claim`. Long-polls for up to 30s; 204 means nothing was claimed.
48 /// The labels are informational: the server uses the labels stored for the runner.48 /// The labels are informational: the server uses the labels stored for the runner.
49-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]49+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
50 pub struct ClaimRequest {50 pub struct ClaimRequest {
51 pub labels: Vec<String>,51 pub labels: Vec<String>,
52+ /// The runner's live job concurrency. Absent from an older runner.
53+ #[serde(default, skip_serializing_if = "Option::is_none")]
54+ pub concurrency: Option<u32>,
55+ /// The runner's version, for the admin page.
56+ #[serde(default, skip_serializing_if = "Option::is_none")]
57+ pub version: Option<String>,
58+ /// Logical CPUs of the runner's host.
59+ #[serde(default, skip_serializing_if = "Option::is_none")]
60+ pub cpus: Option<u32>,
61+ /// Total memory of the runner's host, in bytes.
62+ #[serde(default, skip_serializing_if = "Option::is_none")]
63+ pub memory_bytes: Option<u64>,
52 }64 }
53 65
66+/// Response header on a claim: the concurrency an admin set for this runner in the web UI. Absent
67+/// when there is no override, which means the runner uses the value from its own `runner.toml`.
68+pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency";
69+
70+/// The smallest and largest job concurrency a runner accepts.
71+pub const MIN_CONCURRENCY: u32 = 1;
72+pub const MAX_CONCURRENCY: u32 = 64;
73+
54 /// Returned with 200 by the claim endpoint.74 /// Returned with 200 by the claim endpoint.
55 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]75 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
56 pub struct JobAssignment {76 pub struct JobAssignment {
@@ -108,10 +128,30 @@ impl fmt::Debug for JobAssignment {
108 }128 }
109 }129 }
110 130
131+/// `PUT /api/v1/ci/runners/config`: the runner's effective `runner.toml` as flat JSON by dotted key
132+/// (`limits.memory`). Secrets are redacted by the runner before they get here.
133+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
134+pub struct RunnerConfigReport {
135+ pub config: BTreeMap<String, serde_json::Value>,
136+}
137+
138+/// Response to `GET` and `PUT /api/v1/ci/runners/config`: the values an admin set in the web UI,
139+/// by the same dotted keys. A key that is absent has no override. The runner applies the
140+/// restart-time ones when it starts; `concurrency` and `labels` are live and travel elsewhere.
141+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
142+pub struct RunnerConfigOverrides {
143+ #[serde(default)]
144+ pub overrides: BTreeMap<String, serde_json::Value>,
145+}
146+
111 /// Response to `POST /api/v1/ci/jobs/{id}/heartbeat`.147 /// Response to `POST /api/v1/ci/jobs/{id}/heartbeat`.
112 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]148 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
113 pub struct HeartbeatResponse {149 pub struct HeartbeatResponse {
114 pub cancel: bool,150 pub cancel: bool,
151+ /// The concurrency an admin set in the web UI. Absent means no override (use `runner.toml`).
152+ /// A runner at its limit does not claim, so it learns about a change from its heartbeats.
153+ #[serde(default, skip_serializing_if = "Option::is_none")]
154+ pub concurrency: Option<u32>,
115 }155 }
116 156
117 /// `POST /api/v1/ci/jobs/{id}/finish`.157 /// `POST /api/v1/ci/jobs/{id}/finish`.
@@ -142,6 +182,26 @@ mod tests {
142 assert_eq!(json, "\"cancelled\"");182 assert_eq!(json, "\"cancelled\"");
143 }183 }
144 184
185+ #[test]
186+ fn old_and_new_claim_and_heartbeat_bodies_parse() {
187+ let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap();
188+ assert_eq!(old.concurrency, None);
189+ let new = ClaimRequest {
190+ labels: vec![],
191+ concurrency: Some(2),
192+ version: Some("1.0.0".into()),
193+ cpus: Some(8),
194+ memory_bytes: Some(1 << 33),
195+ };
196+ let back: ClaimRequest =
197+ serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap();
198+ assert_eq!(back, new);
199+ let beat: HeartbeatResponse = serde_json::from_str(r#"{"cancel":false}"#).unwrap();
200+ assert_eq!(beat.concurrency, None);
201+ let json = serde_json::to_string(&beat).unwrap();
202+ assert_eq!(json, r#"{"cancel":false}"#);
203+ }
204+
145 #[test]205 #[test]
146 fn finish_request_round_trips() {206 fn finish_request_round_trips() {
147 let req = FinishRequest {207 let req = FinishRequest {
crates/forge-core/migrations/0044_runner_concurrency.sqladded+11 -0
@@ -0,0 +1,11 @@
1+-- Per-runner job concurrency. `concurrency_override` is set by an admin in the web UI (1 to 64);
2+-- NULL means the runner uses the value from its own runner.toml. The reported_* columns are what the
3+-- runner last said about itself on a claim or heartbeat: its live concurrency and host facts. All
4+-- are NULL until a runner that knows how to report has contacted the forge. The number of jobs a
5+-- runner is running now is counted from ci_jobs, not stored. Applied by store/migrate.rs.
6+
7+ALTER TABLE ci_runners ADD COLUMN concurrency_override INTEGER NULL;
8+ALTER TABLE ci_runners ADD COLUMN reported_concurrency INTEGER NULL;
9+ALTER TABLE ci_runners ADD COLUMN reported_version TEXT NULL;
10+ALTER TABLE ci_runners ADD COLUMN reported_cpus INTEGER NULL;
11+ALTER TABLE ci_runners ADD COLUMN reported_memory_bytes INTEGER NULL;
crates/forge-core/migrations/0045_runner_config.sqladded+8 -0
@@ -0,0 +1,8 @@
1+-- Per-runner config shown and edited in the admin UI. `reported_config` is the runner's effective
2+-- runner.toml as flat JSON (secrets redacted), sent when the runner starts. `config_overrides` is a
3+-- flat JSON object of admin-set values by field key, so a new field needs no migration. Concurrency
4+-- keeps its own column (0044) because it is applied live. Both are NULL until used. Applied by
5+-- store/migrate.rs.
6+
7+ALTER TABLE ci_runners ADD COLUMN reported_config TEXT NULL;
8+ALTER TABLE ci_runners ADD COLUMN config_overrides TEXT NULL;
crates/forge-core/migrations/0046_server_settings.sqladded+9 -0
@@ -0,0 +1,9 @@
1+-- Admin overrides of the server config, layered on the config file: UI override, then file, then
2+-- default. One row per dotted config key (see server_settings.rs), so a new setting needs no
3+-- migration. A secret field's value is sealed with the instance key. Applied by store/migrate.rs.
4+
5+CREATE TABLE server_settings (
6+ key TEXT PRIMARY KEY,
7+ value TEXT NOT NULL,
8+ updated_at TEXT NOT NULL
9+);
crates/forge-core/src/audit.rsmodified+8 -2
@@ -60,6 +60,7 @@ pub enum AuditAction {
60 CiSecretDeleted,60 CiSecretDeleted,
61 CiRunnerRegistered,61 CiRunnerRegistered,
62 CiRunnerDeleted,62 CiRunnerDeleted,
63+ CiRunnerConfigChanged,
63 CiRegistrationTokenCreated,64 CiRegistrationTokenCreated,
64 AdvisoryAlertDismissed,65 AdvisoryAlertDismissed,
65 AdvisoryAlertReopened,66 AdvisoryAlertReopened,
@@ -77,6 +78,7 @@ pub enum AuditAction {
77 DiscussionCommentDeleted,78 DiscussionCommentDeleted,
78 MailSettingsUpdated,79 MailSettingsUpdated,
79 MailTestQueued,80 MailTestQueued,
81+ ServerSettingsUpdated,
80 SnippetCreated,82 SnippetCreated,
81 SnippetUpdated,83 SnippetUpdated,
82 SnippetDeleted,84 SnippetDeleted,
@@ -157,6 +159,7 @@ impl AuditAction {
157 AuditAction::CiSecretDeleted,159 AuditAction::CiSecretDeleted,
158 AuditAction::CiRunnerRegistered,160 AuditAction::CiRunnerRegistered,
159 AuditAction::CiRunnerDeleted,161 AuditAction::CiRunnerDeleted,
162+ AuditAction::CiRunnerConfigChanged,
160 AuditAction::CiRegistrationTokenCreated,163 AuditAction::CiRegistrationTokenCreated,
161 AuditAction::AdvisoryAlertDismissed,164 AuditAction::AdvisoryAlertDismissed,
162 AuditAction::AdvisoryAlertReopened,165 AuditAction::AdvisoryAlertReopened,
@@ -174,6 +177,7 @@ impl AuditAction {
174 AuditAction::DiscussionCommentDeleted,177 AuditAction::DiscussionCommentDeleted,
175 AuditAction::MailSettingsUpdated,178 AuditAction::MailSettingsUpdated,
176 AuditAction::MailTestQueued,179 AuditAction::MailTestQueued,
180+ AuditAction::ServerSettingsUpdated,
177 AuditAction::SnippetCreated,181 AuditAction::SnippetCreated,
178 AuditAction::SnippetUpdated,182 AuditAction::SnippetUpdated,
179 AuditAction::SnippetDeleted,183 AuditAction::SnippetDeleted,
@@ -253,6 +257,7 @@ impl AuditAction {
253 AuditAction::CiSecretDeleted => "ci_secret_deleted",257 AuditAction::CiSecretDeleted => "ci_secret_deleted",
254 AuditAction::CiRunnerRegistered => "ci_runner_registered",258 AuditAction::CiRunnerRegistered => "ci_runner_registered",
255 AuditAction::CiRunnerDeleted => "ci_runner_deleted",259 AuditAction::CiRunnerDeleted => "ci_runner_deleted",
260+ AuditAction::CiRunnerConfigChanged => "ci_runner_config_changed",
256 AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created",261 AuditAction::CiRegistrationTokenCreated => "ci_registration_token_created",
257 AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed",262 AuditAction::AdvisoryAlertDismissed => "advisory_alert_dismissed",
258 AuditAction::AdvisoryAlertReopened => "advisory_alert_reopened",263 AuditAction::AdvisoryAlertReopened => "advisory_alert_reopened",
@@ -270,6 +275,7 @@ impl AuditAction {
270 AuditAction::DiscussionCommentDeleted => "discussion_comment_deleted",275 AuditAction::DiscussionCommentDeleted => "discussion_comment_deleted",
271 AuditAction::MailSettingsUpdated => "mail_settings_updated",276 AuditAction::MailSettingsUpdated => "mail_settings_updated",
272 AuditAction::MailTestQueued => "mail_test_queued",277 AuditAction::MailTestQueued => "mail_test_queued",
278+ AuditAction::ServerSettingsUpdated => "server_settings_updated",
273 AuditAction::SnippetCreated => "snippet_created",279 AuditAction::SnippetCreated => "snippet_created",
274 AuditAction::SnippetUpdated => "snippet_updated",280 AuditAction::SnippetUpdated => "snippet_updated",
275 AuditAction::SnippetDeleted => "snippet_deleted",281 AuditAction::SnippetDeleted => "snippet_deleted",
@@ -390,13 +396,13 @@ mod tests {
390 #[test]396 #[test]
391 fn names_are_unique_and_round_trip() {397 fn names_are_unique_and_round_trip() {
392 let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect();398 let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect();
393- assert_eq!(names.len(), 92);399+ assert_eq!(names.len(), 94);
394 for action in AuditAction::ALL {400 for action in AuditAction::ALL {
395 assert_eq!(AuditAction::parse(action.as_str()), Some(*action));401 assert_eq!(AuditAction::parse(action.as_str()), Some(*action));
396 }402 }
397 names.sort();403 names.sort();
398 names.dedup();404 names.dedup();
399- assert_eq!(names.len(), 92);405+ assert_eq!(names.len(), 94);
400 assert_eq!(AuditAction::parse("nope"), None);406 assert_eq!(AuditAction::parse("nope"), None);
401 }407 }
402 408
crates/forge-core/src/ci.rsmodified+218 -0
@@ -4,6 +4,7 @@
4 //! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and4 //! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and
5 //! `runs_on` arrays out of it, so this crate does not depend on forge-ci.5 //! `runs_on` arrays out of it, so this crate does not depend on forge-ci.
6 6
7+use std::collections::BTreeMap;
7 use std::str::FromStr;8 use std::str::FromStr;
8 9
9 use crate::error::{Error, Result};10 use crate::error::{Error, Result};
@@ -126,8 +127,225 @@ pub struct CiRunner {
126 pub created_at: String,127 pub created_at: String,
127 pub last_seen_at: Option<String>,128 pub last_seen_at: Option<String>,
128 pub disabled: bool,129 pub disabled: bool,
130+ /// The concurrency an admin set in the web UI (1 to 64). `None` means the runner uses the
131+ /// value from its own `runner.toml`.
132+ pub concurrency_override: Option<u32>,
133+ /// What the runner last reported about itself. All `None` for a runner that never has.
134+ pub reported: RunnerReport,
135+ /// Jobs this runner is running now, counted from the job table.
136+ pub running_jobs: u32,
137+ /// The runner's effective config as it last reported it, by field key. Secrets are redacted.
138+ pub reported_config: BTreeMap<String, serde_json::Value>,
139+ /// Admin-set values by field key. A key here beats the runner's own runner.toml.
140+ pub config_overrides: BTreeMap<String, serde_json::Value>,
129 }141 }
130 142
143+/// How a runner config field can be changed from the web UI.
144+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145+pub enum FieldKind {
146+ /// Applied on the runner's next check-in, with no restart.
147+ Live,
148+ /// Stored now, applied when the runner next starts.
149+ Restart,
150+ /// Shown only.
151+ ReadOnly,
152+}
153+
154+/// One field of `runner.toml` as the admin UI sees it. `key` is the dotted TOML path.
155+#[derive(Debug, Clone, Copy)]
156+pub struct RunnerField {
157+ pub key: &'static str,
158+ pub kind: FieldKind,
159+}
160+
161+/// Every field the runner reports, in display order. Identity, the secret and the forge URL are
162+/// read-only: changing them from the forge would lock the runner out. Only `concurrency` and
163+/// `labels` can be applied without a restart, because the forge holds the labels itself and the
164+/// runner resizes its job slots live. Everything else is read once at startup.
165+pub const RUNNER_FIELDS: &[RunnerField] = &[
166+ RunnerField {
167+ key: "concurrency",
168+ kind: FieldKind::Live,
169+ },
170+ RunnerField {
171+ key: "labels",
172+ kind: FieldKind::Live,
173+ },
174+ RunnerField {
175+ key: "auto_update",
176+ kind: FieldKind::Restart,
177+ },
178+ RunnerField {
179+ key: "executor",
180+ kind: FieldKind::Restart,
181+ },
182+ RunnerField {
183+ key: "work_dir",
184+ kind: FieldKind::Restart,
185+ },
186+ RunnerField {
187+ key: "limits.memory",
188+ kind: FieldKind::Restart,
189+ },
190+ RunnerField {
191+ key: "limits.cpus",
192+ kind: FieldKind::Restart,
193+ },
194+ RunnerField {
195+ key: "limits.pids",
196+ kind: FieldKind::Restart,
197+ },
198+ RunnerField {
199+ key: "limits.image_max_gb",
200+ kind: FieldKind::Restart,
201+ },
202+ RunnerField {
203+ key: "images.keep_days",
204+ kind: FieldKind::Restart,
205+ },
206+ RunnerField {
207+ key: "cache_max_gib",
208+ kind: FieldKind::Restart,
209+ },
210+ RunnerField {
211+ key: "sandbox.userns",
212+ kind: FieldKind::Restart,
213+ },
214+ RunnerField {
215+ key: "name",
216+ kind: FieldKind::ReadOnly,
217+ },
218+ RunnerField {
219+ key: "url",
220+ kind: FieldKind::ReadOnly,
221+ },
222+ RunnerField {
223+ key: "runner_id",
224+ kind: FieldKind::ReadOnly,
225+ },
226+ RunnerField {
227+ key: "runner_secret",
228+ kind: FieldKind::ReadOnly,
229+ },
230+ RunnerField {
231+ key: "registry",
232+ kind: FieldKind::ReadOnly,
233+ },
234+];
235+
236+/// The field with this key.
237+pub fn runner_field(key: &str) -> Option<&'static RunnerField> {
238+ RUNNER_FIELDS.iter().find(|f| f.key == key)
239+}
240+
241+fn int_in(
242+ raw: &str,
243+ lo: i64,
244+ hi: i64,
245+ what: &str,
246+) -> std::result::Result<serde_json::Value, String> {
247+ match raw.trim().parse::<i64>() {
248+ Ok(n) if (lo..=hi).contains(&n) => Ok(serde_json::Value::from(n)),
249+ _ => Err(format!("{what} must be a whole number from {lo} to {hi}")),
250+ }
251+}
252+
253+/// Checks `raw` (the text the admin typed) for field `key` and returns the JSON value to store.
254+/// `Err` carries a message for the admin. Read-only and unknown fields are refused.
255+pub fn validate_runner_field(
256+ key: &str,
257+ raw: &str,
258+) -> std::result::Result<serde_json::Value, String> {
259+ use serde_json::Value;
260+ let raw = raw.trim();
261+ match key {
262+ "concurrency" => int_in(
263+ raw,
264+ i64::from(MIN_RUNNER_CONCURRENCY),
265+ i64::from(MAX_RUNNER_CONCURRENCY),
266+ "concurrency",
267+ ),
268+ "labels" => {
269+ let labels: Vec<String> = raw
270+ .split(',')
271+ .map(|l| l.trim().to_owned())
272+ .filter(|l| !l.is_empty())
273+ .collect();
274+ if labels
275+ .iter()
276+ .any(|l| l.len() > 64 || l.contains(char::is_whitespace))
277+ {
278+ return Err("each label is 1 to 64 characters with no spaces".into());
279+ }
280+ Ok(Value::from(labels))
281+ }
282+ "auto_update" => match raw {
283+ "true" => Ok(Value::Bool(true)),
284+ "false" => Ok(Value::Bool(false)),
285+ _ => Err("auto_update must be true or false".into()),
286+ },
287+ "executor" => match raw {
288+ "builtin" | "podman" => Ok(Value::from(raw)),
289+ _ => Err("executor must be builtin or podman".into()),
290+ },
291+ "sandbox.userns" => match raw {
292+ "auto" | "single" | "subuid" => Ok(Value::from(raw)),
293+ _ => Err("userns must be auto, single or subuid".into()),
294+ },
295+ "work_dir" => {
296+ if raw.starts_with('/') && raw.len() <= 512 && !raw.contains('\0') {
297+ Ok(Value::from(raw))
298+ } else {
299+ Err("work_dir must be an absolute path".into())
300+ }
301+ }
302+ "limits.memory" => {
303+ let digits = raw.trim_end_matches(|c: char| c.is_ascii_alphabetic());
304+ let unit = &raw[digits.len()..];
305+ let ok = !digits.is_empty()
306+ && digits.chars().all(|c| c.is_ascii_digit())
307+ && matches!(
308+ unit.to_ascii_lowercase().as_str(),
309+ "" | "b" | "k" | "m" | "g" | "t" | "kb" | "mb" | "gb" | "tb"
310+ );
311+ if ok {
312+ Ok(Value::from(raw))
313+ } else {
314+ Err("memory looks like 4g, 512m or a byte count".into())
315+ }
316+ }
317+ "limits.cpus" => {
318+ let ok = raw.parse::<f64>().is_ok_and(|n| n > 0.0 && n <= 1024.0)
319+ && raw.chars().all(|c| c.is_ascii_digit() || c == '.');
320+ if ok {
321+ Ok(Value::from(raw))
322+ } else {
323+ Err("cpus is a positive number such as 2 or 1.5".into())
324+ }
325+ }
326+ "limits.pids" => int_in(raw, 1, 4_194_304, "pids"),
327+ "limits.image_max_gb" => int_in(raw, 1, 100_000, "image_max_gb"),
328+ "images.keep_days" => int_in(raw, 0, 3650, "keep_days"),
329+ "cache_max_gib" => int_in(raw, 0, 1_000_000, "cache_max_gib"),
330+ _ => Err("this field cannot be changed from the forge".into()),
331+ }
332+}
333+
334+/// Facts a runner reports about itself on a claim or heartbeat. A field the runner did not send is
335+/// `None` and leaves the stored value alone.
336+#[derive(Debug, Clone, Default, PartialEq, Eq)]
337+pub struct RunnerReport {
338+ /// The concurrency the runner is applying right now.
339+ pub concurrency: Option<u32>,
340+ pub version: Option<String>,
341+ pub cpus: Option<u32>,
342+ pub memory_bytes: Option<u64>,
343+}
344+
345+/// The smallest and largest concurrency an admin may set.
346+pub const MIN_RUNNER_CONCURRENCY: u32 = 1;
347+pub const MAX_RUNNER_CONCURRENCY: u32 = 64;
348+
131 /// One run of the workflow for a commit.349 /// One run of the workflow for a commit.
132 #[derive(Debug, Clone, PartialEq, Eq)]350 #[derive(Debug, Clone, PartialEq, Eq)]
133 pub struct CiRun {351 pub struct CiRun {
crates/forge-core/src/config.rsmodified+39 -5
@@ -604,6 +604,12 @@ trusted_proxies = []
604 impl Config {604 impl Config {
605 /// Loads the config from `path`. Writes development defaults if the file is missing.605 /// Loads the config from `path`. Writes development defaults if the file is missing.
606 pub fn load(path: &Path) -> Result<Config> {606 pub fn load(path: &Path) -> Result<Config> {
607+ Self::load_with_keys(path).map(|(config, _)| config)
608+ }
609+
610+ /// Like `load`, and also returns the dotted keys the file sets (such as `ci.max_log_mb`), so the
611+ /// settings page can tell a file value from a default.
612+ pub fn load_with_keys(path: &Path) -> Result<(Config, std::collections::BTreeSet<String>)> {
607 let text = match std::fs::read_to_string(path) {613 let text = match std::fs::read_to_string(path) {
608 Ok(text) => text,614 Ok(text) => text,
609 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {615 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
@@ -617,11 +623,39 @@ impl Config {
617 };623 };
618 let config: Config =624 let config: Config =
619 toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))?;625 toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))?;
620- config.backup.validate()?;626+ config.validate()?;
621- config.replication.validate()?;627+ let mut keys = std::collections::BTreeSet::new();
622- config.self_update.validate()?;628+ if let Ok(table) = text.parse::<toml::Table>() {
623- config.storage.validate()?;629+ flatten_keys("", &table, &mut keys);
624- Ok(config)630+ }
631+ Ok((config, keys))
632+ }
633+
634+ /// The cross-field rules the loader applies after parsing. The settings page runs the same
635+ /// check before it stores an override.
636+ pub fn validate(&self) -> Result<()> {
637+ self.backup.validate()?;
638+ self.replication.validate()?;
639+ self.self_update.validate()?;
640+ self.storage.validate()?;
641+ Ok(())
642+ }
643+}
644+
645+/// Collects the dotted path of every non-table value in `table`.
646+fn flatten_keys(prefix: &str, table: &toml::Table, out: &mut std::collections::BTreeSet<String>) {
647+ for (key, value) in table {
648+ let path = if prefix.is_empty() {
649+ key.clone()
650+ } else {
651+ format!("{prefix}.{key}")
652+ };
653+ match value {
654+ toml::Value::Table(inner) => flatten_keys(&path, inner, out),
655+ _ => {
656+ out.insert(path);
657+ }
658+ }
625 }659 }
626 }660 }
627 661
crates/forge-core/src/lib.rsmodified+1 -0
@@ -24,6 +24,7 @@ pub mod reactions;
24 pub mod releases;24 pub mod releases;
25 pub mod reviews;25 pub mod reviews;
26 pub mod secret;26 pub mod secret;
27+pub mod server_settings;
27 pub mod session;28 pub mod session;
28 pub mod store;29 pub mod store;
29 pub mod time;30 pub mod time;
crates/forge-core/src/server_settings.rsadded+1284 -0
@@ -0,0 +1,1284 @@
1+//! Admin-editable server settings, layered on the config file.
2+//!
3+//! Precedence per field: a UI override (table `server_settings`), then the config file, then the
4+//! built-in default. The config file is never rewritten. Every field has a [`Kind`]:
5+//!
6+//! - `Live`: applied to the running process at once. Consumers read [`Live::current`].
7+//! - `Restart`: saved and shown as pending until the process restarts. Boot layers the stored
8+//! overrides on the file config, so they take effect then.
9+//! - `ReadOnly`: shown, never editable (listen addresses, database path, data dir).
10+//!
11+//! A secret field is write-only: the page shows whether it is set, never the value, and the stored
12+//! value is sealed with the instance key.
13+//!
14+//! Values travel as canonical strings (`true`, `42`, `a, b`) so one table holds every field and a
15+//! new field needs no migration. [`get`] and [`set`] convert between those strings and [`Config`].
16+
17+use std::collections::{BTreeMap, BTreeSet};
18+use std::net::IpAddr;
19+use std::sync::{Arc, RwLock};
20+
21+use ipnet::IpNet;
22+
23+use crate::config::{Config, MailTransport, OrgCreation, Registration, StorageBackend};
24+use crate::error::{Error, Result};
25+
26+/// How a field reaches the running process.
27+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28+pub enum Kind {
29+ Live,
30+ Restart,
31+ ReadOnly,
32+}
33+
34+/// The page tab a field belongs to.
35+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36+pub enum Group {
37+ General,
38+ Limits,
39+ Storage,
40+ Backups,
41+ Integrations,
42+}
43+
44+impl Group {
45+ pub const ALL: [Group; 5] = [
46+ Group::General,
47+ Group::Limits,
48+ Group::Storage,
49+ Group::Backups,
50+ Group::Integrations,
51+ ];
52+
53+ pub fn slug(self) -> &'static str {
54+ match self {
55+ Group::General => "general",
56+ Group::Limits => "limits",
57+ Group::Storage => "storage",
58+ Group::Backups => "backups",
59+ Group::Integrations => "integrations",
60+ }
61+ }
62+
63+ pub fn parse(slug: &str) -> Option<Group> {
64+ Group::ALL.into_iter().find(|g| g.slug() == slug)
65+ }
66+}
67+
68+/// The value type of a field, which decides the input and the server-side check.
69+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70+pub enum Ty {
71+ Bool,
72+ /// Whole number in `min..=max`.
73+ Uint(u64, u64),
74+ Text,
75+ /// A filesystem path. Empty is allowed and usually means "off".
76+ Path,
77+ Choice(&'static [&'static str]),
78+ /// Comma separated entries.
79+ List,
80+ /// Write-only text.
81+ Secret,
82+ /// Socket address (read-only fields only).
83+ Addr,
84+}
85+
86+#[derive(Debug, Clone, Copy)]
87+pub struct Field {
88+ pub key: &'static str,
89+ pub group: Group,
90+ pub kind: Kind,
91+ pub ty: Ty,
92+ pub label: &'static str,
93+ pub help: &'static str,
94+}
95+
96+impl Field {
97+ pub fn is_secret(&self) -> bool {
98+ self.ty == Ty::Secret
99+ }
100+}
101+
102+const fn f(
103+ key: &'static str,
104+ group: Group,
105+ kind: Kind,
106+ ty: Ty,
107+ label: &'static str,
108+ help: &'static str,
109+) -> Field {
110+ Field {
111+ key,
112+ group,
113+ kind,
114+ ty,
115+ label,
116+ help,
117+ }
118+}
119+
120+use Group::{Backups, General, Integrations, Limits, Storage};
121+use Kind::{Live as L, ReadOnly as R, Restart as X};
122+
123+const REGISTRATION: &[&str] = &["closed", "invite", "open"];
124+const ORG_CREATION: &[&str] = &["all", "admin"];
125+const MAIL_TRANSPORT: &[&str] = &["smtp", "log"];
126+const BACKEND: &[&str] = &["fs", "s3", "r2"];
127+const JURISDICTION: &[&str] = &["", "eu", "fedramp"];
128+const MB: Ty = Ty::Uint(1, 1_048_576);
129+const PORT: Ty = Ty::Uint(1, 65_535);
130+
131+/// Every setting, in display order.
132+pub static FIELDS: &[Field] = &[
133+ f(
134+ "registration",
135+ General,
136+ L,
137+ Ty::Choice(REGISTRATION),
138+ "Registration",
139+ "Who may create an account: closed, invite only, or open.",
140+ ),
141+ f(
142+ "orgs.creation",
143+ General,
144+ L,
145+ Ty::Choice(ORG_CREATION),
146+ "Organization creation",
147+ "Who may create an organization: all signed-in people, or admins only.",
148+ ),
149+ f(
150+ "trusted_proxies",
151+ General,
152+ L,
153+ Ty::List,
154+ "Trusted proxies",
155+ "Addresses or CIDR networks whose X-Forwarded-For header is trusted. Comma separated.",
156+ ),
157+ f(
158+ "base_url",
159+ General,
160+ X,
161+ Ty::Text,
162+ "Base URL",
163+ "Public URL used in links and clone URLs.",
164+ ),
165+ f(
166+ "user_content_base_url",
167+ General,
168+ X,
169+ Ty::Text,
170+ "User content URL",
171+ "Separate origin that serves raw user files.",
172+ ),
173+ f(
174+ "ssh_public_host",
175+ General,
176+ X,
177+ Ty::Text,
178+ "SSH host shown",
179+ "Host in SSH clone URLs.",
180+ ),
181+ f(
182+ "ssh_public_port",
183+ General,
184+ X,
185+ PORT,
186+ "SSH port shown",
187+ "Port in SSH clone URLs.",
188+ ),
189+ f(
190+ "listen",
191+ General,
192+ R,
193+ Ty::Addr,
194+ "HTTP listen address",
195+ "Set in the config file.",
196+ ),
197+ f(
198+ "user_content_listen",
199+ General,
200+ R,
201+ Ty::Addr,
202+ "User content listen address",
203+ "Set in the config file.",
204+ ),
205+ f(
206+ "ssh_listen",
207+ General,
208+ R,
209+ Ty::Addr,
210+ "SSH listen address",
211+ "Set in the config file.",
212+ ),
213+ f(
214+ "database",
215+ General,
216+ R,
217+ Ty::Path,
218+ "Database file",
219+ "Set in the config file.",
220+ ),
221+ f(
222+ "data_dir",
223+ General,
224+ R,
225+ Ty::Path,
226+ "Data directory",
227+ "Set in the config file.",
228+ ),
229+ f(
230+ "ci.enabled",
231+ Limits,
232+ L,
233+ Ty::Bool,
234+ "CI enabled",
235+ "When off, pushes and pull requests create no runs.",
236+ ),
237+ f(
238+ "ci.max_log_mb",
239+ Limits,
240+ L,
241+ MB,
242+ "Largest job log (MiB)",
243+ "A longer log is truncated.",
244+ ),
245+ f(
246+ "ci.max_artifact_mb",
247+ Limits,
248+ L,
249+ MB,
250+ "Largest artifact (MiB)",
251+ "",
252+ ),
253+ f(
254+ "ci.max_artifacts_per_job",
255+ Limits,
256+ L,
257+ Ty::Uint(1, 100_000),
258+ "Artifacts per job",
259+ "",
260+ ),
261+ f(
262+ "ci.log_retention_days",
263+ Limits,
264+ L,
265+ Ty::Uint(1, 36_500),
266+ "Log retention (days)",
267+ "",
268+ ),
269+ f(
270+ "ci.artifact_retention_days",
271+ Limits,
272+ L,
273+ Ty::Uint(1, 36_500),
274+ "Artifact retention (days)",
275+ "",
276+ ),
277+ f(
278+ "ci.registration_token_hours",
279+ Limits,
280+ L,
281+ Ty::Uint(1, 8_760),
282+ "Runner token lifetime (hours)",
283+ "How long a runner registration token stays valid.",
284+ ),
285+ f(
286+ "lfs.max_object_mb",
287+ Limits,
288+ L,
289+ MB,
290+ "Largest LFS object (MiB)",
291+ "",
292+ ),
293+ f(
294+ "releases.max_asset_mb",
295+ Limits,
296+ L,
297+ MB,
298+ "Largest release asset (MiB)",
299+ "",
300+ ),
301+ f(
302+ "storage.backend",
303+ Storage,
304+ X,
305+ Ty::Choice(BACKEND),
306+ "Backend",
307+ "Where release assets and CI artifacts live: fs, r2 or s3.",
308+ ),
309+ f(
310+ "storage.r2.account_id",
311+ Storage,
312+ X,
313+ Ty::Text,
314+ "R2 account id",
315+ "32 character hex string from the Cloudflare dashboard.",
316+ ),
317+ f("storage.r2.bucket", Storage, X, Ty::Text, "R2 bucket", ""),
318+ f(
319+ "storage.r2.jurisdiction",
320+ Storage,
321+ X,
322+ Ty::Choice(JURISDICTION),
323+ "R2 jurisdiction",
324+ "eu, fedramp, or empty for the global default.",
325+ ),
326+ f(
327+ "storage.r2.prefix",
328+ Storage,
329+ X,
330+ Ty::Text,
331+ "R2 key prefix",
332+ "",
333+ ),
334+ f(
335+ "storage.r2.access_key_id",
336+ Storage,
337+ X,
338+ Ty::Text,
339+ "R2 access key id",
340+ "",
341+ ),
342+ f(
343+ "storage.r2.secret_access_key_file",
344+ Storage,
345+ X,
346+ Ty::Path,
347+ "R2 secret key file",
348+ "Path of the file that holds the secret access key. The key itself is never read here.",
349+ ),
350+ f("storage.s3.bucket", Storage, X, Ty::Text, "S3 bucket", ""),
351+ f("storage.s3.region", Storage, X, Ty::Text, "S3 region", ""),
352+ f(
353+ "storage.s3.endpoint",
354+ Storage,
355+ X,
356+ Ty::Text,
357+ "S3 endpoint",
358+ "Leave empty for AWS.",
359+ ),
360+ f(
361+ "storage.s3.prefix",
362+ Storage,
363+ X,
364+ Ty::Text,
365+ "S3 key prefix",
366+ "",
367+ ),
368+ f(
369+ "storage.s3.access_key_id",
370+ Storage,
371+ X,
372+ Ty::Text,
373+ "S3 access key id",
374+ "",
375+ ),
376+ f(
377+ "storage.s3.secret_access_key_file",
378+ Storage,
379+ X,
380+ Ty::Path,
381+ "S3 secret key file",
382+ "Path of the file that holds the secret access key.",
383+ ),
384+ f(
385+ "storage.s3.allow_http",
386+ Storage,
387+ X,
388+ Ty::Bool,
389+ "S3 allow http",
390+ "",
391+ ),
392+ f(
393+ "storage.s3.virtual_hosted_style",
394+ Storage,
395+ X,
396+ Ty::Bool,
397+ "S3 virtual hosted style",
398+ "",
399+ ),
400+ f(
401+ "backup.dir",
402+ Backups,
403+ X,
404+ Ty::Path,
405+ "Backup directory",
406+ "Empty turns scheduled backups off.",
407+ ),
408+ f(
409+ "backup.interval_hours",
410+ Backups,
411+ X,
412+ Ty::Uint(1, 8_760),
413+ "Backup interval (hours)",
414+ "",
415+ ),
416+ f(
417+ "backup.keep",
418+ Backups,
419+ X,
420+ Ty::Uint(1, 10_000),
421+ "Backup sets kept",
422+ "",
423+ ),
424+ f(
425+ "backup.fsck_interval_days",
426+ Backups,
427+ X,
428+ Ty::Uint(1, 3_650),
429+ "fsck interval (days)",
430+ "",
431+ ),
432+ f(
433+ "backup.healthcheck_url",
434+ Backups,
435+ X,
436+ Ty::Secret,
437+ "Backup healthcheck URL",
438+ "May hold a token, so it is write-only.",
439+ ),
440+ f(
441+ "replication.target",
442+ Backups,
443+ X,
444+ Ty::Text,
445+ "Replication target",
446+ "Empty turns standby replication off.",
447+ ),
448+ f(
449+ "replication.ssh_port",
450+ Backups,
451+ X,
452+ PORT,
453+ "Replication SSH port",
454+ "",
455+ ),
456+ f(
457+ "replication.identity_file",
458+ Backups,
459+ X,
460+ Ty::Path,
461+ "Replication identity file",
462+ "",
463+ ),
464+ f(
465+ "replication.known_hosts_file",
466+ Backups,
467+ X,
468+ Ty::Path,
469+ "Replication known hosts file",
470+ "",
471+ ),
472+ f(
473+ "replication.db_snapshot_minutes",
474+ Backups,
475+ X,
476+ Ty::Uint(1, 525_600),
477+ "Database snapshot (minutes)",
478+ "",
479+ ),
480+ f(
481+ "replication.reconcile_minutes",
482+ Backups,
483+ X,
484+ Ty::Uint(1, 525_600),
485+ "Reconcile (minutes)",
486+ "",
487+ ),
488+ f(
489+ "replication.healthcheck_url",
490+ Backups,
491+ X,
492+ Ty::Secret,
493+ "Replication healthcheck URL",
494+ "May hold a token, so it is write-only.",
495+ ),
496+ f(
497+ "webhooks.allow_http",
498+ Integrations,
499+ X,
500+ Ty::Bool,
501+ "Allow http webhooks",
502+ "Permit http:// hook URLs besides https://.",
503+ ),
504+ f(
505+ "webhooks.allowed_hosts",
506+ Integrations,
507+ X,
508+ Ty::List,
509+ "Webhook allowed hosts",
510+ "Hostnames or CIDR networks reachable even when they resolve to internal addresses. Comma separated.",
511+ ),
512+ f(
513+ "mail.transport",
514+ Integrations,
515+ X,
516+ Ty::Choice(MAIL_TRANSPORT),
517+ "Mail transport",
518+ "smtp sends mail, log writes it to a directory. The SMTP account is on the Mail page.",
519+ ),
520+ f(
521+ "advisories.enabled",
522+ Integrations,
523+ X,
524+ Ty::Bool,
525+ "Security advisories",
526+ "Download OSV dumps and scan lockfiles.",
527+ ),
528+ f(
529+ "advisories.ecosystems",
530+ Integrations,
531+ X,
532+ Ty::List,
533+ "Advisory ecosystems",
534+ "Any of crates.io, npm, Go. Comma separated.",
535+ ),
536+ f(
537+ "advisories.refresh_hours",
538+ Integrations,
539+ X,
540+ Ty::Uint(1, 8_760),
541+ "Advisory refresh (hours)",
542+ "",
543+ ),
544+ f(
545+ "self_update.enabled",
546+ Integrations,
547+ X,
548+ Ty::Bool,
549+ "Self-update",
550+ "Deploy the artifact of a green run of the forge's own repo.",
551+ ),
552+ f(
553+ "self_update.repo",
554+ Integrations,
555+ X,
556+ Ty::Text,
557+ "Self-update repo",
558+ "As owner/name.",
559+ ),
560+ f(
561+ "self_update.branch",
562+ Integrations,
563+ X,
564+ Ty::Text,
565+ "Self-update branch",
566+ "",
567+ ),
568+ f(
569+ "self_update.job",
570+ Integrations,
571+ X,
572+ Ty::Text,
573+ "Self-update job",
574+ "",
575+ ),
576+ f(
577+ "self_update.artifact",
578+ Integrations,
579+ X,
580+ Ty::Text,
581+ "Self-update artifact",
582+ "",
583+ ),
584+];
585+
586+/// The field for a dotted key.
587+pub fn field(key: &str) -> Option<&'static Field> {
588+ FIELDS.iter().find(|f| f.key == key)
589+}
590+
591+fn invalid(field: &Field, why: &str) -> Error {
592+ Error::Invalid(format!("{}: {why}", field.label))
593+}
594+
595+fn split_list(raw: &str) -> Vec<String> {
596+ raw.split([',', '\n', '\r'])
597+ .map(str::trim)
598+ .filter(|s| !s.is_empty())
599+ .map(str::to_owned)
600+ .collect()
601+}
602+
603+/// Checks `raw` against the field's type and returns its canonical string.
604+pub fn normalize(field: &Field, raw: &str) -> Result<String> {
605+ let raw = raw.trim();
606+ match field.ty {
607+ Ty::Bool => match raw {
608+ "true" | "on" => Ok("true".into()),
609+ "false" | "off" | "" => Ok("false".into()),
610+ _ => Err(invalid(field, "must be on or off")),
611+ },
612+ Ty::Uint(min, max) => {
613+ let n: u64 = raw
614+ .parse()
615+ .map_err(|_| invalid(field, "must be a whole number"))?;
616+ if n < min || n > max {
617+ return Err(invalid(field, &format!("must be between {min} and {max}")));
618+ }
619+ Ok(n.to_string())
620+ }
621+ Ty::Choice(options) => {
622+ if options.contains(&raw) {
623+ Ok(raw.to_owned())
624+ } else {
625+ let shown: Vec<&str> = options
626+ .iter()
627+ .map(|o| if o.is_empty() { "(empty)" } else { o })
628+ .collect();
629+ Err(invalid(
630+ field,
631+ &format!("must be one of {}", shown.join(", ")),
632+ ))
633+ }
634+ }
635+ Ty::Text | Ty::Path | Ty::Secret | Ty::Addr => {
636+ if raw.len() > 1024 || raw.chars().any(char::is_control) {
637+ return Err(invalid(
638+ field,
639+ "must be one line of at most 1024 characters",
640+ ));
641+ }
642+ Ok(raw.to_owned())
643+ }
644+ Ty::List => {
645+ let items = split_list(raw);
646+ if items
647+ .iter()
648+ .any(|i| i.len() > 253 || i.chars().any(char::is_control))
649+ {
650+ return Err(invalid(field, "has an entry that is too long"));
651+ }
652+ if field.key == "trusted_proxies" {
653+ for item in &items {
654+ if item.parse::<IpNet>().is_err() && item.parse::<IpAddr>().is_err() {
655+ return Err(invalid(field, &format!("invalid trusted proxy `{item}`")));
656+ }
657+ }
658+ }
659+ if field.key == "advisories.ecosystems" {
660+ for item in &items {
661+ if !matches!(item.as_str(), "crates.io" | "npm" | "Go") {
662+ return Err(invalid(field, &format!("unknown ecosystem `{item}`")));
663+ }
664+ }
665+ }
666+ Ok(items.join(", "))
667+ }
668+ }
669+}
670+
671+fn b(v: &str) -> bool {
672+ v == "true"
673+}
674+
675+fn n(v: &str) -> u64 {
676+ v.parse().unwrap_or_default()
677+}
678+
679+fn choice<T: Copy>(v: &str, table: &[(&str, T)], fallback: T) -> T {
680+ table
681+ .iter()
682+ .find(|(name, _)| *name == v)
683+ .map_or(fallback, |(_, t)| *t)
684+}
685+
686+fn backend_name(b: StorageBackend) -> &'static str {
687+ match b {
688+ StorageBackend::Fs => "fs",
689+ StorageBackend::S3 => "s3",
690+ StorageBackend::R2 => "r2",
691+ }
692+}
693+
694+/// The canonical string of a field's value in `cfg`. Secrets return their real value, so callers
695+/// that render must not call this for a secret field.
696+pub fn get(cfg: &Config, key: &str) -> String {
697+ let path = |p: &std::path::Path| p.to_string_lossy().into_owned();
698+ let list = |v: &[String]| v.join(", ");
699+ match key {
700+ "registration" => match cfg.registration {
701+ Registration::Closed => "closed",
702+ Registration::Invite => "invite",
703+ Registration::Open => "open",
704+ }
705+ .into(),
706+ "orgs.creation" => match cfg.orgs.creation {
707+ OrgCreation::All => "all",
708+ OrgCreation::Admin => "admin",
709+ }
710+ .into(),
711+ "trusted_proxies" => cfg
712+ .trusted_proxies
713+ .iter()
714+ .map(ToString::to_string)
715+ .collect::<Vec<_>>()
716+ .join(", "),
717+ "base_url" => cfg.base_url.clone(),
718+ "user_content_base_url" => cfg.user_content_base_url.clone(),
719+ "ssh_public_host" => cfg.ssh_public_host.clone(),
720+ "ssh_public_port" => cfg.ssh_public_port.to_string(),
721+ "listen" => cfg.listen.to_string(),
722+ "user_content_listen" => cfg.user_content_listen.to_string(),
723+ "ssh_listen" => cfg.ssh_listen.to_string(),
724+ "database" => path(&cfg.database),
725+ "data_dir" => path(&cfg.data_dir),
726+ "ci.enabled" => cfg.ci.enabled.to_string(),
727+ "ci.max_log_mb" => cfg.ci.max_log_mb.to_string(),
728+ "ci.max_artifact_mb" => cfg.ci.max_artifact_mb.to_string(),
729+ "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job.to_string(),
730+ "ci.log_retention_days" => cfg.ci.log_retention_days.to_string(),
731+ "ci.artifact_retention_days" => cfg.ci.artifact_retention_days.to_string(),
732+ "ci.registration_token_hours" => cfg.ci.registration_token_hours.to_string(),
733+ "lfs.max_object_mb" => cfg.lfs.max_object_mb.to_string(),
734+ "releases.max_asset_mb" => cfg.releases.max_asset_mb.to_string(),
735+ "storage.backend" => backend_name(cfg.storage.backend).into(),
736+ "storage.r2.account_id" => cfg.storage.r2.account_id.clone(),
737+ "storage.r2.bucket" => cfg.storage.r2.bucket.clone(),
738+ "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction.clone(),
739+ "storage.r2.prefix" => cfg.storage.r2.prefix.clone(),
740+ "storage.r2.access_key_id" => cfg.storage.r2.access_key_id.clone(),
741+ "storage.r2.secret_access_key_file" => path(&cfg.storage.r2.secret_access_key_file),
742+ "storage.s3.bucket" => cfg.storage.s3.bucket.clone(),
743+ "storage.s3.region" => cfg.storage.s3.region.clone(),
744+ "storage.s3.endpoint" => cfg.storage.s3.endpoint.clone(),
745+ "storage.s3.prefix" => cfg.storage.s3.prefix.clone(),
746+ "storage.s3.access_key_id" => cfg.storage.s3.access_key_id.clone(),
747+ "storage.s3.secret_access_key_file" => path(&cfg.storage.s3.secret_access_key_file),
748+ "storage.s3.allow_http" => cfg.storage.s3.allow_http.to_string(),
749+ "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style.to_string(),
750+ "backup.dir" => path(&cfg.backup.dir),
751+ "backup.interval_hours" => cfg.backup.interval_hours.to_string(),
752+ "backup.keep" => cfg.backup.keep.to_string(),
753+ "backup.fsck_interval_days" => cfg.backup.fsck_interval_days.to_string(),
754+ "backup.healthcheck_url" => cfg.backup.healthcheck_url.clone(),
755+ "replication.target" => cfg.replication.target.clone(),
756+ "replication.ssh_port" => cfg.replication.ssh_port.to_string(),
757+ "replication.identity_file" => path(&cfg.replication.identity_file),
758+ "replication.known_hosts_file" => path(&cfg.replication.known_hosts_file),
759+ "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes.to_string(),
760+ "replication.reconcile_minutes" => cfg.replication.reconcile_minutes.to_string(),
761+ "replication.healthcheck_url" => cfg.replication.healthcheck_url.clone(),
762+ "webhooks.allow_http" => cfg.webhooks.allow_http.to_string(),
763+ "webhooks.allowed_hosts" => list(&cfg.webhooks.allowed_hosts),
764+ "mail.transport" => match cfg.mail.transport {
765+ MailTransport::Smtp => "smtp",
766+ MailTransport::Log => "log",
767+ }
768+ .into(),
769+ "advisories.enabled" => cfg.advisories.enabled.to_string(),
770+ "advisories.ecosystems" => list(&cfg.advisories.ecosystems),
771+ "advisories.refresh_hours" => cfg.advisories.refresh_hours.to_string(),
772+ "self_update.enabled" => cfg.self_update.enabled.to_string(),
773+ "self_update.repo" => cfg.self_update.repo.clone(),
774+ "self_update.branch" => cfg.self_update.branch.clone(),
775+ "self_update.job" => cfg.self_update.job.clone(),
776+ "self_update.artifact" => cfg.self_update.artifact.clone(),
777+ _ => String::new(),
778+ }
779+}
780+
781+/// Checks `raw` and stores it into `cfg`. A read-only or unknown key is refused.
782+pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> {
783+ let field = field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
784+ if field.kind == Kind::ReadOnly {
785+ return Err(invalid(field, "is read-only"));
786+ }
787+ let v = normalize(field, raw)?;
788+ let v = v.as_str();
789+ let p = || std::path::PathBuf::from(v);
790+ let s = || v.to_owned();
791+ match key {
792+ "registration" => {
793+ cfg.registration = choice(
794+ v,
795+ &[
796+ ("closed", Registration::Closed),
797+ ("invite", Registration::Invite),
798+ ("open", Registration::Open),
799+ ],
800+ Registration::Closed,
801+ )
802+ }
803+ "orgs.creation" => {
804+ cfg.orgs.creation = choice(
805+ v,
806+ &[("all", OrgCreation::All), ("admin", OrgCreation::Admin)],
807+ OrgCreation::All,
808+ )
809+ }
810+ "trusted_proxies" => {
811+ cfg.trusted_proxies = split_list(v)
812+ .iter()
813+ .filter_map(|e| {
814+ e.parse::<IpNet>()
815+ .ok()
816+ .or_else(|| e.parse::<IpAddr>().ok().map(IpNet::from))
817+ })
818+ .collect()
819+ }
820+ "base_url" => cfg.base_url = s(),
821+ "user_content_base_url" => cfg.user_content_base_url = s(),
822+ "ssh_public_host" => cfg.ssh_public_host = s(),
823+ "ssh_public_port" => cfg.ssh_public_port = n(v) as u16,
824+ "ci.enabled" => cfg.ci.enabled = b(v),
825+ "ci.max_log_mb" => cfg.ci.max_log_mb = n(v),
826+ "ci.max_artifact_mb" => cfg.ci.max_artifact_mb = n(v),
827+ "ci.max_artifacts_per_job" => cfg.ci.max_artifacts_per_job = n(v) as u32,
828+ "ci.log_retention_days" => cfg.ci.log_retention_days = n(v),
829+ "ci.artifact_retention_days" => cfg.ci.artifact_retention_days = n(v),
830+ "ci.registration_token_hours" => cfg.ci.registration_token_hours = n(v) as u32,
831+ "lfs.max_object_mb" => cfg.lfs.max_object_mb = n(v),
832+ "releases.max_asset_mb" => cfg.releases.max_asset_mb = n(v),
833+ "storage.backend" => {
834+ cfg.storage.backend = choice(
835+ v,
836+ &[
837+ ("fs", StorageBackend::Fs),
838+ ("s3", StorageBackend::S3),
839+ ("r2", StorageBackend::R2),
840+ ],
841+ StorageBackend::Fs,
842+ )
843+ }
844+ "storage.r2.account_id" => cfg.storage.r2.account_id = s(),
845+ "storage.r2.bucket" => cfg.storage.r2.bucket = s(),
846+ "storage.r2.jurisdiction" => cfg.storage.r2.jurisdiction = s(),
847+ "storage.r2.prefix" => cfg.storage.r2.prefix = s(),
848+ "storage.r2.access_key_id" => cfg.storage.r2.access_key_id = s(),
849+ "storage.r2.secret_access_key_file" => cfg.storage.r2.secret_access_key_file = p(),
850+ "storage.s3.bucket" => cfg.storage.s3.bucket = s(),
851+ "storage.s3.region" => cfg.storage.s3.region = s(),
852+ "storage.s3.endpoint" => cfg.storage.s3.endpoint = s(),
853+ "storage.s3.prefix" => cfg.storage.s3.prefix = s(),
854+ "storage.s3.access_key_id" => cfg.storage.s3.access_key_id = s(),
855+ "storage.s3.secret_access_key_file" => cfg.storage.s3.secret_access_key_file = p(),
856+ "storage.s3.allow_http" => cfg.storage.s3.allow_http = b(v),
857+ "storage.s3.virtual_hosted_style" => cfg.storage.s3.virtual_hosted_style = b(v),
858+ "backup.dir" => cfg.backup.dir = p(),
859+ "backup.interval_hours" => cfg.backup.interval_hours = n(v),
860+ "backup.keep" => cfg.backup.keep = n(v) as usize,
861+ "backup.fsck_interval_days" => cfg.backup.fsck_interval_days = n(v),
862+ "backup.healthcheck_url" => cfg.backup.healthcheck_url = s(),
863+ "replication.target" => cfg.replication.target = s(),
864+ "replication.ssh_port" => cfg.replication.ssh_port = n(v) as u16,
865+ "replication.identity_file" => cfg.replication.identity_file = p(),
866+ "replication.known_hosts_file" => cfg.replication.known_hosts_file = p(),
867+ "replication.db_snapshot_minutes" => cfg.replication.db_snapshot_minutes = n(v),
868+ "replication.reconcile_minutes" => cfg.replication.reconcile_minutes = n(v),
869+ "replication.healthcheck_url" => cfg.replication.healthcheck_url = s(),
870+ "webhooks.allow_http" => cfg.webhooks.allow_http = b(v),
871+ "webhooks.allowed_hosts" => cfg.webhooks.allowed_hosts = split_list(v),
872+ "mail.transport" => {
873+ cfg.mail.transport = choice(
874+ v,
875+ &[("smtp", MailTransport::Smtp), ("log", MailTransport::Log)],
876+ MailTransport::Smtp,
877+ )
878+ }
879+ "advisories.enabled" => cfg.advisories.enabled = b(v),
880+ "advisories.ecosystems" => cfg.advisories.ecosystems = split_list(v),
881+ "advisories.refresh_hours" => cfg.advisories.refresh_hours = n(v),
882+ "self_update.enabled" => cfg.self_update.enabled = b(v),
883+ "self_update.repo" => cfg.self_update.repo = s(),
884+ "self_update.branch" => cfg.self_update.branch = s(),
885+ "self_update.job" => cfg.self_update.job = s(),
886+ "self_update.artifact" => cfg.self_update.artifact = s(),
887+ _ => return Err(Error::Invalid(format!("unknown setting `{key}`"))),
888+ }
889+ Ok(())
890+}
891+
892+/// `file` with every override applied. Read-only keys in `overrides` are ignored. Does not
893+/// validate the result; see [`Config::validate`].
894+pub fn apply(file: &Config, overrides: &BTreeMap<String, String>) -> Result<Config> {
895+ let mut cfg = file.clone();
896+ for (key, value) in overrides {
897+ if field(key).is_some_and(|f| f.kind != Kind::ReadOnly) {
898+ set(&mut cfg, key, value)?;
899+ }
900+ }
901+ Ok(cfg)
902+}
903+
904+/// The config boot runs with: the file plus every stored override. If that combination no longer
905+/// validates (say the file changed under an override), the overrides are dropped and the error is
906+/// returned beside the file config so the caller can log it.
907+pub fn boot_config(file: &Config, overrides: &BTreeMap<String, String>) -> (Config, Option<Error>) {
908+ match apply(file, overrides).and_then(|c| c.validate().map(|()| c)) {
909+ Ok(config) => (config, None),
910+ Err(e) => (file.clone(), Some(e)),
911+ }
912+}
913+
914+/// `boot` with the `Live` fields taken from `pending`: what the running process uses.
915+pub fn live_view(boot: &Config, pending: &Config) -> Config {
916+ let mut cfg = boot.clone();
917+ for f in FIELDS.iter().filter(|f| f.kind == Kind::Live) {
918+ // Values from `get` always pass `normalize`, so this cannot fail.
919+ let _ = set(&mut cfg, f.key, &get(pending, f.key));
920+ }
921+ cfg
922+}
923+
924+/// Where a field's effective value comes from.
925+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
926+pub enum Source {
927+ Default,
928+ File,
929+ Ui,
930+}
931+
932+/// One field as the page shows it.
933+#[derive(Debug, Clone)]
934+pub struct FieldView {
935+ pub field: &'static Field,
936+ /// Effective value. Empty for a secret.
937+ pub value: String,
938+ /// The value the file (or default) gives. Empty for a secret.
939+ pub file_value: String,
940+ pub source: Source,
941+ /// For a secret: whether a value is set.
942+ pub secret_set: bool,
943+ /// Saved but not yet running: a restart field whose value differs from the running one.
944+ pub restart_pending: bool,
945+}
946+
947+/// The process-wide settings handle: the file config, the config boot ran with, and the live view
948+/// consumers read.
949+pub struct Live {
950+ file: Arc<Config>,
951+ file_keys: BTreeSet<String>,
952+ boot: Arc<Config>,
953+ current: RwLock<Arc<Config>>,
954+}
955+
956+impl Live {
957+ pub fn new(file: Arc<Config>, file_keys: BTreeSet<String>, boot: Arc<Config>) -> Live {
958+ Live {
959+ current: RwLock::new(boot.clone()),
960+ file,
961+ file_keys,
962+ boot,
963+ }
964+ }
965+
966+ /// The config the running process uses right now.
967+ pub fn current(&self) -> Arc<Config> {
968+ self.current
969+ .read()
970+ .unwrap_or_else(|poisoned| poisoned.into_inner())
971+ .clone()
972+ }
973+
974+ pub fn file(&self) -> &Config {
975+ &self.file
976+ }
977+
978+ pub fn boot(&self) -> &Config {
979+ &self.boot
980+ }
981+
982+ /// Validates `file + overrides`, then publishes its live fields. Nothing changes on error.
983+ pub fn publish(&self, overrides: &BTreeMap<String, String>) -> Result<()> {
984+ let pending = apply(&self.file, overrides)?;
985+ pending.validate()?;
986+ let live = live_view(&self.boot, &pending);
987+ *self
988+ .current
989+ .write()
990+ .unwrap_or_else(|poisoned| poisoned.into_inner()) = Arc::new(live);
991+ Ok(())
992+ }
993+
994+ /// Every field with its effective value and source.
995+ pub fn views(&self, overrides: &BTreeMap<String, String>) -> Vec<FieldView> {
996+ let pending = apply(&self.file, overrides).unwrap_or_else(|_| (*self.file).clone());
997+ FIELDS
998+ .iter()
999+ .map(|field| {
1000+ let secret = field.is_secret();
1001+ let shown = |cfg: &Config| {
1002+ if secret {
1003+ String::new()
1004+ } else {
1005+ get(cfg, field.key)
1006+ }
1007+ };
1008+ let editable = field.kind != Kind::ReadOnly;
1009+ let source = if editable && overrides.contains_key(field.key) {
1010+ Source::Ui
1011+ } else if self.file_keys.contains(field.key) {
1012+ Source::File
1013+ } else {
1014+ Source::Default
1015+ };
1016+ let effective = if editable { &pending } else { &*self.boot };
1017+ FieldView {
1018+ field,
1019+ value: shown(effective),
1020+ file_value: shown(&self.file),
1021+ source,
1022+ secret_set: secret && !get(effective, field.key).is_empty(),
1023+ restart_pending: field.kind == Kind::Restart
1024+ && get(&pending, field.key) != get(&self.boot, field.key),
1025+ }
1026+ })
1027+ .collect()
1028+ }
1029+
1030+ /// Plans a save of one tab. `submitted` maps key to the raw form value. Returns the keys to
1031+ /// store, the keys to clear (submitted equal to the file value), and the validated result.
1032+ /// A blank secret keeps what is stored. Nothing is stored on error.
1033+ pub fn plan_save(
1034+ &self,
1035+ existing: &BTreeMap<String, String>,
1036+ group: Group,
1037+ submitted: &BTreeMap<String, String>,
1038+ ) -> Result<SavePlan> {
1039+ let before = apply(&self.file, existing)?;
1040+ let mut sets = Vec::new();
1041+ let mut clears = Vec::new();
1042+ let mut next = existing.clone();
1043+ for field in FIELDS
1044+ .iter()
1045+ .filter(|f| f.group == group && f.kind != Kind::ReadOnly)
1046+ {
1047+ let Some(raw) = submitted.get(field.key) else {
1048+ continue;
1049+ };
1050+ if field.is_secret() && raw.trim().is_empty() {
1051+ continue;
1052+ }
1053+ let value = normalize(field, raw)?;
1054+ if field.is_secret() {
1055+ sets.push((field.key.to_owned(), value.clone()));
1056+ next.insert(field.key.to_owned(), value);
1057+ continue;
1058+ }
1059+ let has_override = existing.contains_key(field.key);
1060+ if value == get(&before, field.key) {
1061+ continue;
1062+ }
1063+ if value == get(&self.file, field.key) {
1064+ if has_override {
1065+ clears.push(field.key.to_owned());
1066+ next.remove(field.key);
1067+ }
1068+ continue;
1069+ }
1070+ sets.push((field.key.to_owned(), value.clone()));
1071+ next.insert(field.key.to_owned(), value);
1072+ }
1073+ let pending = apply(&self.file, &next)?;
1074+ pending.validate()?;
1075+ Ok(SavePlan {
1076+ sets,
1077+ clears,
1078+ overrides: next,
1079+ })
1080+ }
1081+
1082+ /// The overrides after dropping `key`, validated.
1083+ pub fn plan_reset(
1084+ &self,
1085+ existing: &BTreeMap<String, String>,
1086+ key: &str,
1087+ ) -> Result<BTreeMap<String, String>> {
1088+ field(key).ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
1089+ let mut next = existing.clone();
1090+ next.remove(key);
1091+ apply(&self.file, &next)?.validate()?;
1092+ Ok(next)
1093+ }
1094+}
1095+
1096+/// The outcome of [`Live::plan_save`].
1097+#[derive(Debug)]
1098+pub struct SavePlan {
1099+ pub sets: Vec<(String, String)>,
1100+ pub clears: Vec<String>,
1101+ /// All overrides once the plan is applied.
1102+ pub overrides: BTreeMap<String, String>,
1103+}
1104+
1105+#[cfg(test)]
1106+mod tests {
1107+ use super::*;
1108+
1109+ fn base() -> Config {
1110+ toml::from_str(
1111+ r#"
1112+database = "/tmp/f.db"
1113+data_dir = "/tmp"
1114+listen = "127.0.0.1:1"
1115+base_url = "http://x"
1116+user_content_base_url = "http://y"
1117+ssh_listen = "127.0.0.1:2"
1118+ssh_public_host = "h"
1119+ssh_public_port = 22
1120+registration = "closed"
1121+[ci]
1122+max_log_mb = 20
1123+"#,
1124+ )
1125+ .expect("config")
1126+ }
1127+
1128+ fn live() -> Live {
1129+ let file = Arc::new(base());
1130+ let keys = ["registration", "ci.max_log_mb"]
1131+ .into_iter()
1132+ .map(String::from)
1133+ .collect();
1134+ Live::new(file.clone(), keys, file)
1135+ }
1136+
1137+ fn form(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
1138+ pairs
1139+ .iter()
1140+ .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1141+ .collect()
1142+ }
1143+
1144+ #[test]
1145+ fn every_field_round_trips_through_get_and_set() {
1146+ let cfg = base();
1147+ for f in FIELDS.iter().filter(|f| f.kind != Kind::ReadOnly) {
1148+ let mut copy = cfg.clone();
1149+ set(&mut copy, f.key, &get(&cfg, f.key)).unwrap_or_else(|e| panic!("{}: {e}", f.key));
1150+ assert_eq!(get(&copy, f.key), get(&cfg, f.key), "{}", f.key);
1151+ }
1152+ }
1153+
1154+ #[test]
1155+ fn precedence_ui_over_file_over_default() {
1156+ let live = live();
1157+ let views = live.views(&BTreeMap::new());
1158+ let find = |views: &[FieldView], key: &str| {
1159+ views.iter().find(|v| v.field.key == key).cloned().unwrap()
1160+ };
1161+ assert_eq!(find(&views, "ci.max_log_mb").source, Source::File);
1162+ assert_eq!(find(&views, "ci.max_log_mb").value, "20");
1163+ assert_eq!(find(&views, "ci.max_artifact_mb").source, Source::Default);
1164+ assert_eq!(find(&views, "ci.max_artifact_mb").value, "512");
1165+
1166+ let over = form(&[("ci.max_log_mb", "99")]);
1167+ let views = live.views(&over);
1168+ let v = find(&views, "ci.max_log_mb");
1169+ assert_eq!(
1170+ (v.source, v.value.as_str(), v.file_value.as_str()),
1171+ (Source::Ui, "99", "20")
1172+ );
1173+ }
1174+
1175+ #[test]
1176+ fn live_fields_apply_and_reset_restores_the_file_value() {
1177+ let live = live();
1178+ assert_eq!(live.current().ci.max_log_mb, 20);
1179+ live.publish(&form(&[("ci.max_log_mb", "99"), ("registration", "open")]))
1180+ .unwrap();
1181+ assert_eq!(live.current().ci.max_log_mb, 99);
1182+ assert_eq!(live.current().registration, Registration::Open);
1183+ let next = live
1184+ .plan_reset(&form(&[("ci.max_log_mb", "99")]), "ci.max_log_mb")
1185+ .unwrap();
1186+ live.publish(&next).unwrap();
1187+ assert_eq!(live.current().ci.max_log_mb, 20);
1188+ }
1189+
1190+ #[test]
1191+ fn restart_fields_do_not_apply_until_boot() {
1192+ let live = live();
1193+ let over = form(&[("base_url", "https://new.example")]);
1194+ live.publish(&over).unwrap();
1195+ assert_eq!(live.current().base_url, "http://x");
1196+ let v = live.views(&over);
1197+ let v = v.iter().find(|v| v.field.key == "base_url").unwrap();
1198+ assert!(v.restart_pending);
1199+ let (boot, err) = boot_config(live.file(), &over);
1200+ assert!(err.is_none());
1201+ assert_eq!(boot.base_url, "https://new.example");
1202+ let after = Live::new(Arc::new(base()), Default::default(), Arc::new(boot));
1203+ assert!(!after.views(&over).iter().any(|v| v.restart_pending));
1204+ }
1205+
1206+ #[test]
1207+ fn validation_rejects_bad_values() {
1208+ let live = live();
1209+ for (key, value) in [
1210+ ("registration", "everyone"),
1211+ ("ci.max_log_mb", "0"),
1212+ ("ci.max_log_mb", "lots"),
1213+ ("trusted_proxies", "not-an-ip"),
1214+ ("ssh_public_port", "70000"),
1215+ ("advisories.ecosystems", "pip"),
1216+ ("storage.r2.jurisdiction", "mars"),
1217+ ("listen", "0.0.0.0:1"),
1218+ ] {
1219+ let mut cfg = base();
1220+ assert!(set(&mut cfg, key, value).is_err(), "{key}={value}");
1221+ }
1222+ // Cross-field loader rules apply to a whole save.
1223+ let group_form = form(&[("storage.backend", "r2")]);
1224+ assert!(
1225+ live.plan_save(&BTreeMap::new(), Group::Storage, &group_form)
1226+ .is_err()
1227+ );
1228+ let group_form = form(&[("backup.dir", "/var/backups"), ("backup.keep", "5")]);
1229+ assert!(
1230+ live.plan_save(&BTreeMap::new(), Group::Backups, &group_form)
1231+ .is_ok()
1232+ );
1233+ }
1234+
1235+ #[test]
1236+ fn save_skips_unchanged_values_and_clears_when_back_at_the_file_value() {
1237+ let live = live();
1238+ let plan = live
1239+ .plan_save(
1240+ &BTreeMap::new(),
1241+ Group::Limits,
1242+ &form(&[
1243+ ("ci.max_log_mb", "20"),
1244+ ("ci.max_artifact_mb", "512"),
1245+ ("ci.enabled", "false"),
1246+ ]),
1247+ )
1248+ .unwrap();
1249+ assert_eq!(
1250+ plan.sets,
1251+ vec![("ci.enabled".to_owned(), "false".to_owned())]
1252+ );
1253+ let existing = form(&[("ci.max_log_mb", "99")]);
1254+ let plan = live
1255+ .plan_save(&existing, Group::Limits, &form(&[("ci.max_log_mb", "20")]))
1256+ .unwrap();
1257+ assert_eq!(plan.clears, vec!["ci.max_log_mb".to_owned()]);
1258+ assert!(plan.overrides.is_empty());
1259+ }
1260+
1261+ #[test]
1262+ fn secrets_are_never_in_a_view_and_blank_keeps_the_stored_value() {
1263+ let live = live();
1264+ let existing = form(&[("backup.healthcheck_url", "https://hc.example/token-123")]);
1265+ let views = live.views(&existing);
1266+ let v = views
1267+ .iter()
1268+ .find(|v| v.field.key == "backup.healthcheck_url")
1269+ .unwrap();
1270+ assert!(v.secret_set && v.value.is_empty() && v.file_value.is_empty());
1271+ let plan = live
1272+ .plan_save(
1273+ &existing,
1274+ Group::Backups,
1275+ &form(&[("backup.healthcheck_url", "")]),
1276+ )
1277+ .unwrap();
1278+ assert!(plan.sets.is_empty());
1279+ assert_eq!(plan.overrides, existing);
1280+ for view in &views {
1281+ assert!(!view.value.contains("token-123"));
1282+ }
1283+ }
1284+}
crates/forge-core/src/store/ci.rsmodified+431 -2
@@ -13,7 +13,10 @@ use super::{
13 Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,13 Store, col_blob, col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,
14 finish, insert_err, missing_row, new_id,14 finish, insert_err, missing_row, new_id,
15 };15 };
16-use crate::ci::{CiArtifact, CiJob, CiRun, CiRunner, JobState, NewJob, RunState};16+use crate::ci::{
17+ CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobState, MAX_RUNNER_CONCURRENCY,
18+ MIN_RUNNER_CONCURRENCY, NewJob, RunState, RunnerReport, validate_runner_field,
19+};
17 use crate::error::{Error, Result};20 use crate::error::{Error, Result};
18 use crate::secret;21 use crate::secret;
19 use crate::time::{now_stamp, stamp_after};22 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
23 started_at, finished_at, heartbeat_at, cancel_requested, log_bytes";26 started_at, finished_at, heartbeat_at, cancel_requested, log_bytes";
24 const RUN_COLS: &str = "id, repo_id, number, trigger, git_ref, commit_oid, pull_number, actor_id, \27 const RUN_COLS: &str = "id, repo_id, number, trigger, git_ref, commit_oid, pull_number, actor_id, \
25 state, config_error, created_at, finished_at";28 state, config_error, created_at, finished_at";
26-const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled";29+const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled, \
30+ concurrency_override, reported_concurrency, reported_version, reported_cpus, \
31+ reported_memory_bytes, reported_config, config_overrides, \
32+ (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running')";
27 const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at";33 const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at";
28 34
29 /// Longest runner name, in bytes.35 /// Longest runner name, in bytes.
@@ -64,9 +70,31 @@ fn map_runner(row: &Row) -> Result<CiRunner> {
64 created_at: col_text(row, 3)?,70 created_at: col_text(row, 3)?,
65 last_seen_at: col_opt_text(row, 4)?,71 last_seen_at: col_opt_text(row, 4)?,
66 disabled: col_bool(row, 5)?,72 disabled: col_bool(row, 5)?,
73+ concurrency_override: opt_u32(row, 6)?,
74+ reported: RunnerReport {
75+ concurrency: opt_u32(row, 7)?,
76+ version: col_opt_text(row, 8)?,
77+ cpus: opt_u32(row, 9)?,
78+ memory_bytes: opt_int(row, 10)?.and_then(|n| u64::try_from(n).ok()),
79+ },
80+ running_jobs: opt_u32(row, 13)?.unwrap_or(0),
81+ reported_config: json_map(row, 11)?,
82+ config_overrides: json_map(row, 12)?,
67 })83 })
68 }84 }
69 85
86+/// A NULL-able column holding a flat JSON object. Bad or missing JSON reads as empty.
87+fn json_map(row: &Row, i: usize) -> Result<BTreeMap<String, serde_json::Value>> {
88+ Ok(col_opt_text(row, i)?
89+ .and_then(|text| serde_json::from_str(&text).ok())
90+ .unwrap_or_default())
91+}
92+
93+/// A NULL-able integer column that holds a count.
94+fn opt_u32(row: &Row, i: usize) -> Result<Option<u32>> {
95+ Ok(opt_int(row, i)?.and_then(|n| u32::try_from(n).ok()))
96+}
97+
70 fn map_run(row: &Row) -> Result<CiRun> {98 fn map_run(row: &Row) -> Result<CiRun> {
71 Ok(CiRun {99 Ok(CiRun {
72 id: col_text(row, 0)?,100 id: col_text(row, 0)?,
@@ -464,6 +492,194 @@ impl Store {
464 Ok(())492 Ok(())
465 }493 }
466 494
495+ /// Sets (`Some`) or clears (`None`) the admin's concurrency override for a runner. The value
496+ /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist.
497+ pub async fn set_runner_concurrency(&self, id: &str, value: Option<u32>) -> Result<()> {
498+ if let Some(n) = value
499+ && !(MIN_RUNNER_CONCURRENCY..=MAX_RUNNER_CONCURRENCY).contains(&n)
500+ {
501+ return Err(Error::Invalid(format!(
502+ "concurrency must be {MIN_RUNNER_CONCURRENCY} to {MAX_RUNNER_CONCURRENCY}"
503+ )));
504+ }
505+ let conn = self.inner.conn.lock().await;
506+ let n = conn
507+ .execute(
508+ "UPDATE ci_runners SET concurrency_override = ?2 WHERE id = ?1",
509+ (id.to_string(), opt_int_value(value.map(i64::from))),
510+ )
511+ .await
512+ .map_err(db_err)?;
513+ if n == 0 {
514+ return Err(Error::NotFound);
515+ }
516+ Ok(())
517+ }
518+
519+ /// Sets (`Some(text)`) or clears (`None`) the admin override of one runner config field. The
520+ /// text is checked by [`validate_runner_field`]; read-only fields and bad values are `Invalid`.
521+ /// `concurrency` goes to its own column and `labels` also replaces the labels the runner claims
522+ /// with. Clearing `labels` restores the labels the runner reported. `NotFound` if the runner is
523+ /// gone.
524+ pub async fn set_runner_field(&self, id: &str, key: &str, value: Option<&str>) -> Result<()> {
525+ let field = crate::ci::runner_field(key)
526+ .filter(|f| f.kind != FieldKind::ReadOnly)
527+ .ok_or_else(|| Error::Invalid("this field cannot be changed from the forge".into()))?;
528+ let parsed = match value {
529+ Some(raw) => Some(validate_runner_field(key, raw).map_err(Error::Invalid)?),
530+ None => None,
531+ };
532+ if field.key == "concurrency" {
533+ let n = parsed.as_ref().and_then(serde_json::Value::as_u64);
534+ return self
535+ .set_runner_concurrency(id, n.and_then(|n| u32::try_from(n).ok()))
536+ .await;
537+ }
538+ let conn = self.inner.conn.lock().await;
539+ let mut runner = fetch_opt(
540+ &conn,
541+ &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"),
542+ (id.to_string(),),
543+ map_runner,
544+ )
545+ .await?
546+ .ok_or(Error::NotFound)?;
547+ match parsed {
548+ Some(v) => {
549+ runner.config_overrides.insert(key.to_owned(), v);
550+ }
551+ None => {
552+ runner.config_overrides.remove(key);
553+ }
554+ }
555+ let overrides = if runner.config_overrides.is_empty() {
556+ Value::Null
557+ } else {
558+ text(
559+ &serde_json::to_string(&runner.config_overrides)
560+ .map_err(|e| Error::Database(e.to_string()))?,
561+ )
562+ };
563+ // The forge claims with the labels it stores, so a labels override is live at once.
564+ let labels = if key == "labels" {
565+ let chosen = runner
566+ .config_overrides
567+ .get("labels")
568+ .or_else(|| runner.reported_config.get("labels"));
569+ chosen.and_then(|v| serde_json::from_value::<Vec<String>>(v.clone()).ok())
570+ } else {
571+ None
572+ };
573+ if let Some(labels) = labels {
574+ conn.execute(
575+ "UPDATE ci_runners SET config_overrides = ?2, labels = ?3 WHERE id = ?1",
576+ (
577+ id.to_string(),
578+ overrides,
579+ text(
580+ &serde_json::to_string(&labels)
581+ .map_err(|e| Error::Database(e.to_string()))?,
582+ ),
583+ ),
584+ )
585+ .await
586+ .map_err(db_err)?;
587+ } else {
588+ conn.execute(
589+ "UPDATE ci_runners SET config_overrides = ?2 WHERE id = ?1",
590+ (id.to_string(), overrides),
591+ )
592+ .await
593+ .map_err(db_err)?;
594+ }
595+ Ok(())
596+ }
597+
598+ /// Stores the runner's effective config (secrets already redacted by the runner). Returns true
599+ /// when it differs from what was stored.
600+ pub async fn set_runner_reported_config(
601+ &self,
602+ id: &str,
603+ config: &BTreeMap<String, serde_json::Value>,
604+ ) -> Result<bool> {
605+ let conn = self.inner.conn.lock().await;
606+ let current = fetch_opt(
607+ &conn,
608+ &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"),
609+ (id.to_string(),),
610+ map_runner,
611+ )
612+ .await?;
613+ let Some(current) = current else {
614+ return Ok(false);
615+ };
616+ if &current.reported_config == config {
617+ return Ok(false);
618+ }
619+ conn.execute(
620+ "UPDATE ci_runners SET reported_config = ?2 WHERE id = ?1",
621+ (
622+ id.to_string(),
623+ text(&serde_json::to_string(config).map_err(|e| Error::Database(e.to_string()))?),
624+ ),
625+ )
626+ .await
627+ .map_err(db_err)?;
628+ Ok(true)
629+ }
630+
631+ /// The runner's concurrency override, read fresh. `None` when unset or the runner is gone.
632+ pub async fn runner_concurrency_override(&self, id: &str) -> Result<Option<u32>> {
633+ let conn = self.read_conn().await;
634+ let found = fetch_opt(
635+ &conn,
636+ "SELECT concurrency_override FROM ci_runners WHERE id = ?1",
637+ (id.to_string(),),
638+ |row| opt_u32(row, 0),
639+ )
640+ .await?;
641+ Ok(found.flatten())
642+ }
643+
644+ /// Stores what a runner reported about itself. Fields that are `None` keep their stored
645+ /// value. Returns true when a stored value changed, so the caller can tell live pages.
646+ pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> {
647+ let conn = self.inner.conn.lock().await;
648+ let current = fetch_opt(
649+ &conn,
650+ &format!("SELECT {RUNNER_COLS} FROM ci_runners WHERE id = ?1"),
651+ (id.to_string(),),
652+ map_runner,
653+ )
654+ .await?;
655+ let Some(current) = current else {
656+ return Ok(false);
657+ };
658+ let merged = RunnerReport {
659+ concurrency: report.concurrency.or(current.reported.concurrency),
660+ version: report.version.clone().or(current.reported.version.clone()),
661+ cpus: report.cpus.or(current.reported.cpus),
662+ memory_bytes: report.memory_bytes.or(current.reported.memory_bytes),
663+ };
664+ if merged == current.reported {
665+ return Ok(false);
666+ }
667+ conn.execute(
668+ "UPDATE ci_runners SET reported_concurrency = ?2, reported_version = ?3, \
669+ reported_cpus = ?4, reported_memory_bytes = ?5 WHERE id = ?1",
670+ (
671+ id.to_string(),
672+ opt_int_value(merged.concurrency.map(i64::from)),
673+ opt_text(merged.version.as_deref()),
674+ opt_int_value(merged.cpus.map(i64::from)),
675+ opt_int_value(merged.memory_bytes.and_then(|n| i64::try_from(n).ok())),
676+ ),
677+ )
678+ .await
679+ .map_err(db_err)?;
680+ Ok(true)
681+ }
682+
467 /// Removes a runner. `NotFound` if it does not exist.683 /// Removes a runner. `NotFound` if it does not exist.
468 pub async fn delete_runner(&self, id: &str) -> Result<()> {684 pub async fn delete_runner(&self, id: &str) -> Result<()> {
469 let conn = self.inner.conn.lock().await;685 let conn = self.inner.conn.lock().await;
@@ -1279,6 +1495,11 @@ mod tests {
1279 created_at: now_stamp(),1495 created_at: now_stamp(),
1280 last_seen_at: None,1496 last_seen_at: None,
1281 disabled: false,1497 disabled: false,
1498+ concurrency_override: None,
1499+ reported: RunnerReport::default(),
1500+ running_jobs: 0,
1501+ reported_config: BTreeMap::new(),
1502+ config_overrides: BTreeMap::new(),
1282 }1503 }
1283 }1504 }
1284 1505
@@ -1336,6 +1557,214 @@ mod tests {
1336 ));1557 ));
1337 }1558 }
1338 1559
1560+ #[tokio::test]
1561+ async fn concurrency_override_is_set_validated_and_cleared() {
1562+ let fx = fixture().await;
1563+ let (runner, secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await;
1564+ assert_eq!(runner.concurrency_override, None);
1565+
1566+ fx.store
1567+ .set_runner_concurrency(&runner.id, Some(4))
1568+ .await
1569+ .unwrap();
1570+ let found = fx.store.runner_by_secret(&secret).await.unwrap().unwrap();
1571+ assert_eq!(found.concurrency_override, Some(4));
1572+ assert_eq!(
1573+ fx.store
1574+ .runner_concurrency_override(&runner.id)
1575+ .await
1576+ .unwrap(),
1577+ Some(4)
1578+ );
1579+
1580+ for bad in [0, 65, 1000] {
1581+ assert!(matches!(
1582+ fx.store.set_runner_concurrency(&runner.id, Some(bad)).await,
1583+ Err(Error::Invalid(_))
1584+ ));
1585+ }
1586+ assert_eq!(
1587+ fx.store.list_runners().await.unwrap()[0].concurrency_override,
1588+ Some(4),
1589+ "a rejected value changes nothing"
1590+ );
1591+ for edge in [1, 64] {
1592+ fx.store
1593+ .set_runner_concurrency(&runner.id, Some(edge))
1594+ .await
1595+ .unwrap();
1596+ }
1597+
1598+ fx.store
1599+ .set_runner_concurrency(&runner.id, None)
1600+ .await
1601+ .unwrap();
1602+ assert_eq!(
1603+ fx.store
1604+ .runner_concurrency_override(&runner.id)
1605+ .await
1606+ .unwrap(),
1607+ None
1608+ );
1609+ assert!(matches!(
1610+ fx.store.set_runner_concurrency("missing", Some(2)).await,
1611+ Err(Error::NotFound)
1612+ ));
1613+ }
1614+
1615+ #[tokio::test]
1616+ async fn config_field_overrides_validate_and_labels_are_live() {
1617+ let fx = fixture().await;
1618+ let (runner, secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await;
1619+ let reported: BTreeMap<String, serde_json::Value> = [
1620+ ("labels".to_owned(), serde_json::json!(["linux"])),
1621+ ("limits.memory".to_owned(), serde_json::json!("4g")),
1622+ ]
1623+ .into();
1624+ assert!(
1625+ fx.store
1626+ .set_runner_reported_config(&runner.id, &reported)
1627+ .await
1628+ .unwrap()
1629+ );
1630+ assert!(
1631+ !fx.store
1632+ .set_runner_reported_config(&runner.id, &reported)
1633+ .await
1634+ .unwrap()
1635+ );
1636+
1637+ fx.store
1638+ .set_runner_field(&runner.id, "limits.memory", Some("8g"))
1639+ .await
1640+ .unwrap();
1641+ for (key, bad) in [
1642+ ("limits.memory", "lots"),
1643+ ("limits.pids", "0"),
1644+ ("executor", "docker"),
1645+ ("work_dir", "relative/path"),
1646+ ("url", "https://evil.example"),
1647+ ("runner_secret", "x"),
1648+ ("nonsense", "1"),
1649+ ] {
1650+ assert!(
1651+ matches!(
1652+ fx.store.set_runner_field(&runner.id, key, Some(bad)).await,
1653+ Err(Error::Invalid(_))
1654+ ),
1655+ "{key}={bad}"
1656+ );
1657+ }
1658+ let found = fx.store.runner_by_secret(&secret).await.unwrap().unwrap();
1659+ assert_eq!(found.config_overrides["limits.memory"], "8g");
1660+ assert_eq!(found.reported_config["limits.memory"], "4g");
1661+
1662+ // Labels are claimed with at once, and a reset restores what the runner reported.
1663+ fx.store
1664+ .set_runner_field(&runner.id, "labels", Some("linux, arm"))
1665+ .await
1666+ .unwrap();
1667+ let after = fx.store.list_runners().await.unwrap().remove(0);
1668+ assert_eq!(after.labels, vec!["linux".to_string(), "arm".to_string()]);
1669+ fx.store
1670+ .set_runner_field(&runner.id, "labels", None)
1671+ .await
1672+ .unwrap();
1673+ fx.store
1674+ .set_runner_field(&runner.id, "limits.memory", None)
1675+ .await
1676+ .unwrap();
1677+ let after = fx.store.list_runners().await.unwrap().remove(0);
1678+ assert_eq!(after.labels, vec!["linux".to_string()]);
1679+ assert!(after.config_overrides.is_empty());
1680+
1681+ // Concurrency goes through the same entry point.
1682+ fx.store
1683+ .set_runner_field(&runner.id, "concurrency", Some("6"))
1684+ .await
1685+ .unwrap();
1686+ assert_eq!(
1687+ fx.store.list_runners().await.unwrap()[0].concurrency_override,
1688+ Some(6)
1689+ );
1690+ assert!(matches!(
1691+ fx.store
1692+ .set_runner_field(&runner.id, "concurrency", Some("65"))
1693+ .await,
1694+ Err(Error::Invalid(_))
1695+ ));
1696+ }
1697+
1698+ #[tokio::test]
1699+ async fn runner_report_round_trip_and_running_count() {
1700+ let fx = fixture().await;
1701+ let (runner, _secret) = runner_with(&fx.store, &fx.tahinli.id, &["linux"]).await;
1702+ assert_eq!(runner.reported, RunnerReport::default());
1703+
1704+ let full = RunnerReport {
1705+ concurrency: Some(2),
1706+ version: Some("0.9.1".into()),
1707+ cpus: Some(8),
1708+ memory_bytes: Some(16 << 30),
1709+ };
1710+ assert!(
1711+ fx.store
1712+ .record_runner_report(&runner.id, &full)
1713+ .await
1714+ .unwrap()
1715+ );
1716+ assert!(
1717+ !fx.store
1718+ .record_runner_report(&runner.id, &full)
1719+ .await
1720+ .unwrap(),
1721+ "an identical report is not a change"
1722+ );
1723+ // A heartbeat reports only the concurrency and keeps the host facts.
1724+ let beat = RunnerReport {
1725+ concurrency: Some(3),
1726+ ..RunnerReport::default()
1727+ };
1728+ assert!(
1729+ fx.store
1730+ .record_runner_report(&runner.id, &beat)
1731+ .await
1732+ .unwrap()
1733+ );
1734+ let listed = fx.store.list_runners().await.unwrap().remove(0);
1735+ assert_eq!(
1736+ listed.reported,
1737+ RunnerReport {
1738+ concurrency: Some(3),
1739+ ..full
1740+ }
1741+ );
1742+ assert_eq!(listed.running_jobs, 0);
1743+
1744+ // The running count comes from the job table, and drops when the job finishes.
1745+ create(
1746+ &fx.store,
1747+ &fx.repo.id,
1748+ &fx.tahinli.id,
1749+ &[job("one", &[], &[])],
1750+ false,
1751+ )
1752+ .await;
1753+ let (claimed, _, _) = fx.store.claim_job(&runner).await.unwrap().unwrap();
1754+ assert_eq!(fx.store.list_runners().await.unwrap()[0].running_jobs, 1);
1755+ fx.store
1756+ .finish_job(&claimed.id, JobState::Success, Some(0), None)
1757+ .await
1758+ .unwrap();
1759+ assert_eq!(fx.store.list_runners().await.unwrap()[0].running_jobs, 0);
1760+ assert!(
1761+ !fx.store
1762+ .record_runner_report("missing", &beat)
1763+ .await
1764+ .unwrap()
1765+ );
1766+ }
1767+
1339 #[tokio::test]1768 #[tokio::test]
1340 async fn runner_secret_lookup_and_disable() {1769 async fn runner_secret_lookup_and_disable() {
1341 let fx = fixture().await;1770 let fx = fixture().await;
crates/forge-core/src/store/migrate.rsmodified+9 -0
@@ -62,6 +62,15 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
62 (41, include_str!("../../migrations/0041_accent.sql")),62 (41, include_str!("../../migrations/0041_accent.sql")),
63 (42, include_str!("../../migrations/0042_colours.sql")),63 (42, include_str!("../../migrations/0042_colours.sql")),
64 (43, include_str!("../../migrations/0043_sidebar_side.sql")),64 (43, include_str!("../../migrations/0043_sidebar_side.sql")),
65+ (
66+ 44,
67+ include_str!("../../migrations/0044_runner_concurrency.sql"),
68+ ),
69+ (45, include_str!("../../migrations/0045_runner_config.sql")),
70+ (
71+ 46,
72+ include_str!("../../migrations/0046_server_settings.sql"),
73+ ),
65 ];74 ];
66 75
67 /// The highest migration version this binary knows about.76 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+1 -0
@@ -28,6 +28,7 @@ pub mod releases;
28 pub mod replication;28 pub mod replication;
29 pub mod repo_listing;29 pub mod repo_listing;
30 pub mod reviews;30 pub mod reviews;
31+pub mod server_settings;
31 pub mod signatures;32 pub mod signatures;
32 pub mod snapshot;33 pub mod snapshot;
33 pub mod snippets;34 pub mod snippets;
crates/forge-core/src/store/server_settings.rsadded+85 -0
@@ -0,0 +1,85 @@
1+//! Storage for the admin overrides of the server config (migration 0046). One row per dotted key.
2+//! The key set and the value rules live in `server_settings`; this layer only moves strings, and
3+//! seals the value of a secret field with the instance key.
4+
5+use std::collections::BTreeMap;
6+
7+use super::{Store, col_text, db_err, fetch_all};
8+use crate::error::{Error, Result};
9+use crate::{secret, server_settings};
10+
11+impl Store {
12+ fn settings_key(&self) -> Result<[u8; 32]> {
13+ self.inner
14+ .secret_key
15+ .get()
16+ .copied()
17+ .ok_or_else(|| Error::Crypto("the instance key is not set".into()))
18+ }
19+
20+ /// Every stored override, with secret values opened. A key this binary does not know is
21+ /// skipped, so an override written by a newer version does not break an older one.
22+ pub async fn server_overrides(&self) -> Result<BTreeMap<String, String>> {
23+ let rows = {
24+ let conn = self.read_conn().await;
25+ fetch_all(&conn, "SELECT key, value FROM server_settings", (), |row| {
26+ Ok((col_text(row, 0)?, col_text(row, 1)?))
27+ })
28+ .await?
29+ };
30+ let mut out = BTreeMap::new();
31+ for (key, value) in rows {
32+ let Some(field) = server_settings::field(&key) else {
33+ continue;
34+ };
35+ let value = if field.is_secret() {
36+ let plain = secret::open(&self.settings_key()?, &value)?;
37+ String::from_utf8(plain)
38+ .map_err(|_| Error::Crypto("a sealed setting is not text".into()))?
39+ } else {
40+ value
41+ };
42+ out.insert(key, value);
43+ }
44+ Ok(out)
45+ }
46+
47+ /// Stores overrides, replacing any existing value for the same keys. Unknown keys are refused.
48+ pub async fn set_server_overrides(&self, entries: &[(String, String)]) -> Result<()> {
49+ let now = crate::time::now_stamp();
50+ let mut prepared = Vec::with_capacity(entries.len());
51+ for (key, value) in entries {
52+ let field = server_settings::field(key)
53+ .ok_or_else(|| Error::Invalid(format!("unknown setting `{key}`")))?;
54+ let stored = if field.is_secret() {
55+ secret::seal(&self.settings_key()?, value.as_bytes())?
56+ } else {
57+ value.clone()
58+ };
59+ prepared.push((key.clone(), stored));
60+ }
61+ let conn = self.inner.conn.lock().await;
62+ for (key, stored) in prepared {
63+ conn.execute(
64+ "INSERT INTO server_settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
65+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
66+ (key, stored, now.clone()),
67+ )
68+ .await
69+ .map_err(db_err)?;
70+ }
71+ Ok(())
72+ }
73+
74+ /// Removes the override of `key`, so the file value (or the default) applies again.
75+ pub async fn clear_server_override(&self, key: &str) -> Result<()> {
76+ let conn = self.inner.conn.lock().await;
77+ conn.execute(
78+ "DELETE FROM server_settings WHERE key = ?1",
79+ (key.to_owned(),),
80+ )
81+ .await
82+ .map_err(db_err)?;
83+ Ok(())
84+ }
85+}
crates/forge-runner/src/cli.rsmodified+29 -1
@@ -223,7 +223,8 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
223 Some(p) => p,223 Some(p) => p,
224 None => config::default_config_path()?,224 None => config::default_config_path()?,
225 };225 };
226- let cfg = config::load(&path)?;226+ let mut cfg = config::load(&path)?;
227+ sync_config_with_forge(&mut cfg).await;
227 let shutdown = CancellationToken::new();228 let shutdown = CancellationToken::new();
228 let cache_root = cfg.work_dir.join(".cache");229 let cache_root = cfg.work_dir.join(".cache");
229 let cache_cap = cfg.cache_max_gib;230 let cache_cap = cfg.cache_max_gib;
@@ -343,3 +344,30 @@ fn spawn_image_gc(
343 fn gib(gb: u64) -> u64 {344 fn gib(gb: u64) -> u64 {
344 gb.saturating_mul(1024 * 1024 * 1024)345 gb.saturating_mul(1024 * 1024 * 1024)
345 }346 }
347+
348+/// Applies the admin's startup-time overrides from the forge to `cfg` and reports the effective
349+/// config back for the admin page. Best effort: an older forge, or a forge that cannot be reached,
350+/// leaves `runner.toml` as it is and the runner starts anyway.
351+async fn sync_config_with_forge(cfg: &mut RunnerConfig) {
352+ let client = match crate::client::ForgeClient::new(&cfg.url) {
353+ Ok(client) => client,
354+ Err(e) => {
355+ tracing::warn!(error = %e, "cannot sync config with the forge");
356+ return;
357+ }
358+ };
359+ match client.get_config(&cfg.runner_secret).await {
360+ Ok(reply) => {
361+ for line in cfg.apply_overrides(&reply.overrides) {
362+ tracing::info!("{line}");
363+ }
364+ }
365+ Err(e) => tracing::warn!(error = %e, "cannot read config overrides, using runner.toml"),
366+ }
367+ let report = forge_ci::proto::RunnerConfigReport {
368+ config: cfg.report(),
369+ };
370+ if let Err(e) = client.put_config(&cfg.runner_secret, &report).await {
371+ tracing::warn!(error = %e, "cannot report config to the forge");
372+ }
373+}
crates/forge-runner/src/client.rsmodified+128 -7
@@ -7,8 +7,8 @@ use std::path::Path;
7 use std::time::Duration;7 use std::time::Duration;
8 8
9 use forge_ci::proto::{9 use forge_ci::proto::{
10- ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, RegisterRequest,10+ CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment,
11- RegisterResponse,11+ RegisterRequest, RegisterResponse, RunnerConfigOverrides, RunnerConfigReport,
12 };12 };
13 use reqwest::StatusCode;13 use reqwest::StatusCode;
14 use reqwest::header::{CONTENT_LENGTH, HeaderMap};14 use reqwest::header::{CONTENT_LENGTH, HeaderMap};
@@ -30,6 +30,7 @@ const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target";
30 const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256";30 const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256";
31 /// `GET`: the forge's binary, for a runner that is updating itself.31 /// `GET`: the forge's binary, for a runner that is updating itself.
32 const BINARY_PATH: &str = "/api/v1/ci/runners/binary";32 const BINARY_PATH: &str = "/api/v1/ci/runners/binary";
33+const CONFIG_PATH: &str = "/api/v1/ci/runners/config";
33 34
34 /// Errors from talking to the forge.35 /// Errors from talking to the forge.
35 #[derive(Debug, thiserror::Error)]36 #[derive(Debug, thiserror::Error)]
@@ -60,6 +61,8 @@ pub struct ClaimReply {
60 pub job: Option<JobAssignment>,61 pub job: Option<JobAssignment>,
61 /// The sha256 (lowercase hex) of the forge's binary, when the response advertises one.62 /// The sha256 (lowercase hex) of the forge's binary, when the response advertises one.
62 pub binary_sha256: Option<String>,63 pub binary_sha256: Option<String>,
64+ /// The concurrency an admin set in the web UI. `None` means no override.
65+ pub concurrency: Option<u32>,
63 }66 }
64 67
65 /// A client for one forge base URL.68 /// A client for one forge base URL.
@@ -104,8 +107,24 @@ impl ForgeClient {
104 runner_secret: &str,107 runner_secret: &str,
105 labels: &[String],108 labels: &[String],
106 ) -> Result<ClaimReply, ClientError> {109 ) -> Result<ClaimReply, ClientError> {
110+ self.claim_with(runner_secret, labels, None).await
111+ }
112+
113+ /// Like [`ForgeClient::claim`], and also reports the runner's live `concurrency` and its host
114+ /// facts (version, CPUs, memory) for the forge's admin page.
115+ pub async fn claim_with(
116+ &self,
117+ runner_secret: &str,
118+ labels: &[String],
119+ concurrency: Option<usize>,
120+ ) -> Result<ClaimReply, ClientError> {
121+ let host = host_facts();
107 let req = ClaimRequest {122 let req = ClaimRequest {
108 labels: labels.to_vec(),123 labels: labels.to_vec(),
124+ concurrency: concurrency.and_then(|n| u32::try_from(n).ok()),
125+ version: Some(env!("CARGO_PKG_VERSION").to_owned()),
126+ cpus: host.cpus,
127+ memory_bytes: host.memory_bytes,
109 };128 };
110 let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS);129 let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS);
111 let resp = self130 let resp = self
@@ -118,19 +137,54 @@ impl ForgeClient {
118 .send()137 .send()
119 .await?;138 .await?;
120 let binary_sha256 = advertised_sha256(resp.headers());139 let binary_sha256 = advertised_sha256(resp.headers());
140+ let concurrency = advertised_concurrency(resp.headers());
121 match resp.status() {141 match resp.status() {
122 StatusCode::NO_CONTENT => Ok(ClaimReply {142 StatusCode::NO_CONTENT => Ok(ClaimReply {
123 job: None,143 job: None,
124 binary_sha256,144 binary_sha256,
145+ concurrency,
125 }),146 }),
126 status if status.is_success() => Ok(ClaimReply {147 status if status.is_success() => Ok(ClaimReply {
127 job: Some(resp.json().await?),148 job: Some(resp.json().await?),
128 binary_sha256,149 binary_sha256,
150+ concurrency,
129 }),151 }),
130 _ => Err(status_error(resp).await),152 _ => Err(status_error(resp).await),
131 }153 }
132 }154 }
133 155
156+ /// `GET /api/v1/ci/runners/config`: the overrides an admin set for this runner.
157+ pub async fn get_config(
158+ &self,
159+ runner_secret: &str,
160+ ) -> Result<RunnerConfigOverrides, ClientError> {
161+ let resp = self
162+ .http
163+ .get(self.url(CONFIG_PATH))
164+ .bearer_auth(runner_secret)
165+ .timeout(REQUEST_TIMEOUT)
166+ .send()
167+ .await?;
168+ json_or_error(resp).await
169+ }
170+
171+ /// `PUT /api/v1/ci/runners/config`: reports the runner's effective config (secrets redacted).
172+ pub async fn put_config(
173+ &self,
174+ runner_secret: &str,
175+ report: &RunnerConfigReport,
176+ ) -> Result<RunnerConfigOverrides, ClientError> {
177+ let resp = self
178+ .http
179+ .put(self.url(CONFIG_PATH))
180+ .bearer_auth(runner_secret)
181+ .json(report)
182+ .timeout(REQUEST_TIMEOUT)
183+ .send()
184+ .await?;
185+ json_or_error(resp).await
186+ }
187+
134 /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the188 /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the
135 /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised189 /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised
136 /// value and syncs the file.190 /// value and syncs the file.
@@ -200,14 +254,25 @@ impl ForgeClient {
200 job_id: &str,254 job_id: &str,
201 job_token: &str,255 job_token: &str,
202 ) -> Result<HeartbeatResponse, ClientError> {256 ) -> Result<HeartbeatResponse, ClientError> {
203- let resp = self257+ self.heartbeat_with(job_id, job_token, None).await
258+ }
259+
260+ /// Like [`ForgeClient::heartbeat`], and also tells the forge the runner's live `concurrency`.
261+ pub async fn heartbeat_with(
262+ &self,
263+ job_id: &str,
264+ job_token: &str,
265+ concurrency: Option<usize>,
266+ ) -> Result<HeartbeatResponse, ClientError> {
267+ let mut req = self
204 .http268 .http
205 .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/heartbeat")))269 .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/heartbeat")))
206 .bearer_auth(job_token)270 .bearer_auth(job_token)
207- .timeout(REQUEST_TIMEOUT)271+ .timeout(REQUEST_TIMEOUT);
208- .send()272+ if let Some(n) = concurrency {
209- .await?;273+ req = req.header(CONCURRENCY_HEADER, n.to_string());
210- json_or_error(resp).await274+ }
275+ json_or_error(req.send().await?).await
211 }276 }
212 277
213 /// `PUT /api/v1/ci/jobs/{id}/artifacts/{name}`, streaming the file from disk.278 /// `PUT /api/v1/ci/jobs/{id}/artifacts/{name}`, streaming the file from disk.
@@ -270,6 +335,40 @@ fn advertised_sha256(headers: &HeaderMap) -> Option<String> {
270 .filter(|v| !v.is_empty())335 .filter(|v| !v.is_empty())
271 }336 }
272 337
338+/// The `Forge-Runner-Concurrency` header, when it holds a number.
339+fn advertised_concurrency(headers: &HeaderMap) -> Option<u32> {
340+ headers
341+ .get(CONCURRENCY_HEADER)?
342+ .to_str()
343+ .ok()?
344+ .trim()
345+ .parse()
346+ .ok()
347+}
348+
349+/// Cheap facts about the host that help an admin size the runner's concurrency.
350+struct HostFacts {
351+ cpus: Option<u32>,
352+ memory_bytes: Option<u64>,
353+}
354+
355+fn host_facts() -> HostFacts {
356+ let cpus = std::thread::available_parallelism()
357+ .ok()
358+ .and_then(|n| u32::try_from(n.get()).ok());
359+ let memory_bytes = std::fs::read_to_string("/proc/meminfo")
360+ .ok()
361+ .and_then(|text| parse_mem_total(&text));
362+ HostFacts { cpus, memory_bytes }
363+}
364+
365+/// `MemTotal` of `/proc/meminfo`, in bytes. The file reports kibibytes.
366+fn parse_mem_total(meminfo: &str) -> Option<u64> {
367+ let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?;
368+ let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
369+ kib.checked_mul(1024)
370+}
371+
273 async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T, ClientError> {372 async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T, ClientError> {
274 if resp.status().is_success() {373 if resp.status().is_success() {
275 Ok(resp.json().await?)374 Ok(resp.json().await?)
@@ -289,3 +388,25 @@ async fn status_error(resp: reqwest::Response) -> ClientError {
289 .collect();388 .collect();
290 ClientError::Status { status, body }389 ClientError::Status { status, body }
291 }390 }
391+
392+#[cfg(test)]
393+mod tests {
394+ use super::*;
395+
396+ #[test]
397+ fn reads_mem_total_in_bytes() {
398+ let text = "MemTotal: 16384 kB\nMemFree: 100 kB\n";
399+ assert_eq!(parse_mem_total(text), Some(16384 * 1024));
400+ assert_eq!(parse_mem_total("nothing"), None);
401+ }
402+
403+ #[test]
404+ fn concurrency_header_must_be_a_number() {
405+ let mut headers = HeaderMap::new();
406+ assert_eq!(advertised_concurrency(&headers), None);
407+ headers.insert(CONCURRENCY_HEADER, "3".parse().unwrap());
408+ assert_eq!(advertised_concurrency(&headers), Some(3));
409+ headers.insert(CONCURRENCY_HEADER, "many".parse().unwrap());
410+ assert_eq!(advertised_concurrency(&headers), None);
411+ }
412+}
crates/forge-runner/src/config.rsmodified+180 -0
@@ -1,5 +1,6 @@
1 //! The runner's `runner.toml`: the forge URL, the runner identity and secret, and local limits.1 //! The runner's `runner.toml`: the forge URL, the runner identity and secret, and local limits.
2 2
3+use std::collections::BTreeMap;
3 use std::fmt;4 use std::fmt;
4 use std::fs::OpenOptions;5 use std::fs::OpenOptions;
5 use std::io::Write;6 use std::io::Write;
@@ -220,6 +221,144 @@ impl RunnerConfig {
220 }221 }
221 }222 }
222 223
224+impl RunnerConfig {
225+ /// The effective config as flat JSON by dotted key, for the forge's admin page. The runner
226+ /// secret and registry passwords are never included: the secret shows as `<redacted>` and a
227+ /// registry shows only as `host (username)`.
228+ pub fn report(&self) -> BTreeMap<String, serde_json::Value> {
229+ use serde_json::json;
230+ let mut m = BTreeMap::new();
231+ m.insert("url".into(), json!(self.url));
232+ m.insert("runner_id".into(), json!(self.runner_id));
233+ m.insert("runner_secret".into(), json!("<redacted>"));
234+ m.insert("name".into(), json!(self.name));
235+ m.insert("labels".into(), json!(self.labels));
236+ m.insert(
237+ "work_dir".into(),
238+ json!(self.work_dir.display().to_string()),
239+ );
240+ m.insert("concurrency".into(), json!(self.concurrency));
241+ m.insert("limits.memory".into(), json!(self.limits.memory));
242+ m.insert("limits.cpus".into(), json!(self.limits.cpus));
243+ m.insert("limits.pids".into(), json!(self.limits.pids));
244+ m.insert(
245+ "limits.image_max_gb".into(),
246+ json!(self.limits.image_max_gb),
247+ );
248+ let executor = match self.executor {
249+ ExecutorKind::Builtin => "builtin",
250+ ExecutorKind::Podman => "podman",
251+ };
252+ m.insert("executor".into(), json!(executor));
253+ m.insert("images.keep_days".into(), json!(self.images.keep_days));
254+ let userns = match self.sandbox.userns {
255+ UsernsMode::Auto => "auto",
256+ UsernsMode::Single => "single",
257+ UsernsMode::Subuid => "subuid",
258+ };
259+ m.insert("sandbox.userns".into(), json!(userns));
260+ m.insert("auto_update".into(), json!(self.auto_update));
261+ m.insert("cache_max_gib".into(), json!(self.cache_max_gib));
262+ let registries: Vec<String> = self
263+ .registries
264+ .iter()
265+ .map(|r| format!("{} ({})", r.host, r.username))
266+ .collect();
267+ m.insert("registry".into(), json!(registries));
268+ m
269+ }
270+
271+ /// Applies the admin's overrides from the forge to this in-memory config, for the fields that
272+ /// are read at startup. `runner.toml` on disk is not touched. A value that does not fit is
273+ /// skipped. Returns one line per field that changed. `concurrency` and `labels` are live and
274+ /// handled elsewhere, and fields that are not listed here are ignored.
275+ pub fn apply_overrides(
276+ &mut self,
277+ overrides: &BTreeMap<String, serde_json::Value>,
278+ ) -> Vec<String> {
279+ let mut changed = Vec::new();
280+ let before = self.clone();
281+ for (key, value) in overrides {
282+ let ok = match key.as_str() {
283+ "auto_update" => value.as_bool().map(|v| self.auto_update = v).is_some(),
284+ "work_dir" => value
285+ .as_str()
286+ .map(|v| self.work_dir = PathBuf::from(v))
287+ .is_some(),
288+ "limits.memory" => value
289+ .as_str()
290+ .map(|v| self.limits.memory = v.to_owned())
291+ .is_some(),
292+ "limits.cpus" => value
293+ .as_str()
294+ .map(|v| self.limits.cpus = v.to_owned())
295+ .is_some(),
296+ "limits.pids" => value
297+ .as_u64()
298+ .and_then(|v| u32::try_from(v).ok())
299+ .map(|v| self.limits.pids = v)
300+ .is_some(),
301+ "limits.image_max_gb" => value
302+ .as_u64()
303+ .map(|v| self.limits.image_max_gb = v)
304+ .is_some(),
305+ "images.keep_days" => value
306+ .as_u64()
307+ .and_then(|v| u32::try_from(v).ok())
308+ .map(|v| self.images.keep_days = v)
309+ .is_some(),
310+ "cache_max_gib" => value.as_u64().map(|v| self.cache_max_gib = v).is_some(),
311+ "executor" => match value.as_str() {
312+ Some("builtin") => {
313+ self.executor = ExecutorKind::Builtin;
314+ true
315+ }
316+ Some("podman") => {
317+ self.executor = ExecutorKind::Podman;
318+ true
319+ }
320+ _ => false,
321+ },
322+ "sandbox.userns" => match value.as_str() {
323+ Some("auto") => {
324+ self.sandbox.userns = UsernsMode::Auto;
325+ true
326+ }
327+ Some("single") => {
328+ self.sandbox.userns = UsernsMode::Single;
329+ true
330+ }
331+ Some("subuid") => {
332+ self.sandbox.userns = UsernsMode::Subuid;
333+ true
334+ }
335+ _ => false,
336+ },
337+ _ => continue,
338+ };
339+ if !ok {
340+ tracing::warn!(field = %key, "ignoring a config override with the wrong type");
341+ }
342+ }
343+ if self.validate().is_err() {
344+ tracing::warn!("config overrides from the forge do not validate, ignoring them");
345+ *self = before;
346+ return changed;
347+ }
348+ let (old, new) = (before.report(), self.report());
349+ for (key, value) in &new {
350+ if old.get(key) != Some(value) {
351+ changed.push(format!(
352+ "runner: {key} {} -> {} (set from server)",
353+ old.get(key).map_or_else(String::new, ToString::to_string),
354+ value
355+ ));
356+ }
357+ }
358+ changed
359+ }
360+}
361+
223 /// The default config path: `$HOME/.config/forge-runner/runner.toml`.362 /// The default config path: `$HOME/.config/forge-runner/runner.toml`.
224 pub fn default_config_path() -> Result<PathBuf, ConfigError> {363 pub fn default_config_path() -> Result<PathBuf, ConfigError> {
225 let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?;364 let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?;
@@ -271,6 +410,47 @@ pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> {
271 410
272 #[cfg(test)]411 #[cfg(test)]
273 mod tests {412 mod tests {
413+ #[test]
414+ fn report_redacts_secrets() {
415+ let dir = tempfile::tempdir().expect("tempdir");
416+ let mut config = sample(dir.path());
417+ config.registries.push(RegistryConfig {
418+ host: "ghcr.io".into(),
419+ username: "tahinli".into(),
420+ password: "hunter2-pass".into(),
421+ });
422+ let text = serde_json::to_string(&config.report()).unwrap();
423+ assert!(!text.contains(&config.runner_secret));
424+ assert!(!text.contains("hunter2-pass"));
425+ assert!(text.contains("ghcr.io (tahinli)"));
426+ assert!(text.contains("limits.memory"));
427+ }
428+
429+ #[test]
430+ fn overrides_apply_and_bad_ones_are_dropped() {
431+ let dir = tempfile::tempdir().expect("tempdir");
432+ let mut config = sample(dir.path());
433+ let mut ov = BTreeMap::new();
434+ ov.insert("limits.memory".to_owned(), serde_json::json!("8g"));
435+ ov.insert("cache_max_gib".to_owned(), serde_json::json!(5));
436+ ov.insert("concurrency".to_owned(), serde_json::json!(9));
437+ let lines = config.apply_overrides(&ov);
438+ assert_eq!(config.limits.memory, "8g");
439+ assert_eq!(config.cache_max_gib, 5);
440+ assert_ne!(
441+ config.concurrency, 9,
442+ "concurrency is live, not a startup override"
443+ );
444+ assert_eq!(lines.len(), 2, "{lines:?}");
445+
446+ // A value that breaks validation drops the whole set and keeps the config.
447+ let before = config.clone();
448+ let mut bad = BTreeMap::new();
449+ bad.insert("limits.image_max_gb".to_owned(), serde_json::json!(0));
450+ assert!(config.apply_overrides(&bad).is_empty());
451+ assert_eq!(config, before);
452+ }
453+
274 use super::*;454 use super::*;
275 455
276 fn sample(dir: &Path) -> RunnerConfig {456 fn sample(dir: &Path) -> RunnerConfig {
crates/forge-runner/src/lib.rsmodified+1 -0
@@ -11,6 +11,7 @@ pub mod cli;
11 pub mod client;11 pub mod client;
12 pub mod config;12 pub mod config;
13 pub mod executor;13 pub mod executor;
14+pub mod limiter;
14 pub mod logs;15 pub mod logs;
15 pub mod oci;16 pub mod oci;
16 pub mod runner;17 pub mod runner;
crates/forge-runner/src/limiter.rsadded+181 -0
@@ -0,0 +1,181 @@
1+//! The runner's live job concurrency. A tokio semaphore holds one permit per job slot. The limit
2+//! can change while jobs run: growing adds permits, shrinking takes back the idle ones at once and
3+//! the rest as running jobs finish. A running job is never killed to make room.
4+
5+use std::sync::{Arc, Mutex, PoisonError};
6+
7+use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY};
8+use tokio::sync::{OwnedSemaphorePermit, Semaphore};
9+
10+/// A resizable job limit. Cheap to share: clone the `Arc`.
11+pub struct Limiter {
12+ semaphore: Arc<Semaphore>,
13+ /// The value from `runner.toml`, used when the forge has no override.
14+ base: usize,
15+ state: Mutex<State>,
16+}
17+
18+struct State {
19+ /// The limit now.
20+ current: usize,
21+ /// Permits still to be taken back after a shrink, because jobs hold them. Each is forgotten
22+ /// instead of released when the job that holds one finishes.
23+ debt: usize,
24+}
25+
26+/// A job slot. Dropping it frees the slot, or retires it when the limit was lowered.
27+pub struct Slot {
28+ permit: Option<OwnedSemaphorePermit>,
29+ limiter: Arc<Limiter>,
30+}
31+
32+impl Drop for Slot {
33+ fn drop(&mut self) {
34+ if let Some(permit) = self.permit.take() {
35+ self.limiter.release(permit);
36+ }
37+ }
38+}
39+
40+/// Clamps a requested concurrency to the range the forge accepts.
41+pub fn clamp(n: usize) -> usize {
42+ n.clamp(MIN_CONCURRENCY as usize, MAX_CONCURRENCY as usize)
43+}
44+
45+impl Limiter {
46+ /// A limiter starting at `base`, which is also the fallback when the forge sends no override.
47+ pub fn new(base: usize) -> Arc<Self> {
48+ let base = clamp(base);
49+ Arc::new(Self {
50+ semaphore: Arc::new(Semaphore::new(base)),
51+ base,
52+ state: Mutex::new(State {
53+ current: base,
54+ debt: 0,
55+ }),
56+ })
57+ }
58+
59+ /// The limit now.
60+ pub fn current(&self) -> usize {
61+ self.lock().current
62+ }
63+
64+ fn lock(&self) -> std::sync::MutexGuard<'_, State> {
65+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
66+ }
67+
68+ /// Waits for a free slot. `Err` when the semaphore is closed, which only happens at teardown.
69+ pub async fn acquire(self: &Arc<Self>) -> Result<Slot, tokio::sync::AcquireError> {
70+ let permit = self.semaphore.clone().acquire_owned().await?;
71+ Ok(Slot {
72+ permit: Some(permit),
73+ limiter: self.clone(),
74+ })
75+ }
76+
77+ /// Applies what the forge asked for: `Some(n)` is an override, `None` means no override and
78+ /// brings back the `runner.toml` value. Returns `(old, new)` when the limit changed.
79+ pub fn apply(&self, desired: Option<u32>) -> Option<(usize, usize)> {
80+ let target = desired.map_or(self.base, |n| clamp(n as usize));
81+ let mut state = self.lock();
82+ let old = state.current;
83+ if target == old {
84+ return None;
85+ }
86+ if target > old {
87+ let mut grow = target - old;
88+ // Permits owed from an earlier shrink are simply kept.
89+ let cancel = grow.min(state.debt);
90+ state.debt -= cancel;
91+ grow -= cancel;
92+ self.semaphore.add_permits(grow);
93+ } else {
94+ let shrink = old - target;
95+ let taken = self.semaphore.forget_permits(shrink);
96+ state.debt += shrink - taken;
97+ }
98+ state.current = target;
99+ Some((old, target))
100+ }
101+
102+ /// Like [`Limiter::apply`], and logs one line when the limit changes.
103+ pub fn apply_logged(&self, desired: Option<u32>) {
104+ if let Some((old, new)) = self.apply(desired) {
105+ let from = if desired.is_some() {
106+ "set from server"
107+ } else {
108+ "back to runner.toml"
109+ };
110+ tracing::info!("runner: concurrency {old} -> {new} ({from})");
111+ }
112+ }
113+
114+ fn release(&self, permit: OwnedSemaphorePermit) {
115+ let mut state = self.lock();
116+ if state.debt > 0 {
117+ state.debt -= 1;
118+ permit.forget();
119+ }
120+ // Otherwise the permit drops here and the slot is free again.
121+ }
122+}
123+
124+#[cfg(test)]
125+mod tests {
126+ use super::*;
127+
128+ #[tokio::test]
129+ async fn grows_and_shrinks_without_touching_running_jobs() {
130+ let limiter = Limiter::new(1);
131+ let a = limiter.acquire().await.unwrap();
132+ assert_eq!(limiter.apply(Some(3)), Some((1, 3)));
133+ assert_eq!(limiter.apply(Some(3)), None, "no change, no log");
134+ let b = limiter.acquire().await.unwrap();
135+ let c = limiter.acquire().await.unwrap();
136+ assert_eq!(limiter.semaphore.available_permits(), 0);
137+
138+ // Shrink to 1 while all 3 slots are busy: nothing is killed, the slots retire on finish.
139+ assert_eq!(limiter.apply(Some(1)), Some((3, 1)));
140+ assert_eq!(limiter.current(), 1);
141+ drop(b);
142+ drop(c);
143+ assert_eq!(limiter.semaphore.available_permits(), 0, "both retired");
144+ drop(a);
145+ assert_eq!(limiter.semaphore.available_permits(), 1, "one slot stays");
146+ }
147+
148+ #[tokio::test]
149+ async fn idle_permits_are_taken_back_at_once() {
150+ let limiter = Limiter::new(4);
151+ let held = limiter.acquire().await.unwrap();
152+ assert_eq!(limiter.apply(Some(2)), Some((4, 2)));
153+ assert_eq!(limiter.semaphore.available_permits(), 1);
154+ drop(held);
155+ assert_eq!(limiter.semaphore.available_permits(), 2);
156+ }
157+
158+ #[tokio::test]
159+ async fn growing_cancels_owed_retirements() {
160+ let limiter = Limiter::new(3);
161+ let slots = [
162+ limiter.acquire().await.unwrap(),
163+ limiter.acquire().await.unwrap(),
164+ limiter.acquire().await.unwrap(),
165+ ];
166+ limiter.apply(Some(1));
167+ limiter.apply(Some(3));
168+ drop(slots);
169+ assert_eq!(limiter.semaphore.available_permits(), 3);
170+ assert_eq!(limiter.current(), 3);
171+ }
172+
173+ #[tokio::test]
174+ async fn no_override_returns_to_the_config_value_and_values_are_clamped() {
175+ let limiter = Limiter::new(2);
176+ assert_eq!(limiter.apply(Some(500)), Some((2, 64)));
177+ assert_eq!(limiter.apply(Some(0)), Some((64, 1)));
178+ assert_eq!(limiter.apply(None), Some((1, 2)));
179+ assert_eq!(limiter.apply(None), None);
180+ }
181+}
crates/forge-runner/src/runner.rsmodified+23 -7
@@ -6,7 +6,7 @@ use std::time::Duration;
6 6
7 use forge_ci::mask::{MaskStream, Masker};7 use forge_ci::mask::{MaskStream, Masker};
8 use forge_ci::proto::{FinishRequest, JobAssignment, Outcome};8 use forge_ci::proto::{FinishRequest, JobAssignment, Outcome};
9-use tokio::sync::{Semaphore, mpsc};9+use tokio::sync::mpsc;
10 use tokio::task::{JoinHandle, JoinSet};10 use tokio::task::{JoinHandle, JoinSet};
11 use tokio::time::Instant;11 use tokio::time::Instant;
12 use tokio_util::sync::CancellationToken;12 use tokio_util::sync::CancellationToken;
@@ -16,6 +16,7 @@ use crate::cache::CacheStore;
16 use crate::client::{ClientError, ForgeClient};16 use crate::client::{ClientError, ForgeClient};
17 use crate::config::RunnerConfig;17 use crate::config::RunnerConfig;
18 use crate::executor::{ExecRequest, ExecResult, Executor};18 use crate::executor::{ExecRequest, ExecResult, Executor};
19+use crate::limiter::Limiter;
19 use crate::logs::{self, PumpConfig};20 use crate::logs::{self, PumpConfig};
20 use crate::update::{self, Installed, UpdateState};21 use crate::update::{self, Installed, UpdateState};
21 use crate::workspace;22 use crate::workspace;
@@ -66,6 +67,8 @@ pub struct Runner {
66 options: RunOptions,67 options: RunOptions,
67 /// The build cache, when it is on. See [`CacheStore`].68 /// The build cache, when it is on. See [`CacheStore`].
68 cache: Option<Arc<CacheStore>>,69 cache: Option<Arc<CacheStore>>,
70+ /// The live job limit. Starts at `runner.toml` and follows the forge's override.
71+ limiter: Arc<Limiter>,
69 }72 }
70 73
71 impl Runner {74 impl Runner {
@@ -75,12 +78,14 @@ impl Runner {
75 options: RunOptions,78 options: RunOptions,
76 ) -> Result<Self, ClientError> {79 ) -> Result<Self, ClientError> {
77 let client = ForgeClient::new(&config.url)?;80 let client = ForgeClient::new(&config.url)?;
81+ let limiter = Limiter::new(config.concurrency);
78 Ok(Self {82 Ok(Self {
79 client,83 client,
80 config: Arc::new(config),84 config: Arc::new(config),
81 executor,85 executor,
82 options,86 options,
83 cache: None,87 cache: None,
88+ limiter,
84 })89 })
85 }90 }
86 91
@@ -101,7 +106,6 @@ impl Runner {
101 /// claimed. Once the running jobs finish, the binary is replaced and the loop returns106 /// claimed. Once the running jobs finish, the binary is replaced and the loop returns
102 /// [`RunEnd::Updated`].107 /// [`RunEnd::Updated`].
103 pub async fn run(&self, shutdown: CancellationToken) -> RunEnd {108 pub async fn run(&self, shutdown: CancellationToken) -> RunEnd {
104- let semaphore = Arc::new(Semaphore::new(self.config.concurrency));
105 let mut jobs: JoinSet<()> = JoinSet::new();109 let mut jobs: JoinSet<()> = JoinSet::new();
106 // Hashed once at startup. Without it, or with auto_update off, updates stay disabled.110 // Hashed once at startup. Without it, or with auto_update off, updates stay disabled.
107 let exe = if self.config.auto_update {111 let exe = if self.config.auto_update {
@@ -121,7 +125,7 @@ impl Runner {
121 );125 );
122 tracing::info!(126 tracing::info!(
123 name = %self.config.name,127 name = %self.config.name,
124- concurrency = self.config.concurrency,128+ concurrency = self.limiter.current(),
125 auto_update = updates.enabled(),129 auto_update = updates.enabled(),
126 "runner started"130 "runner started"
127 );131 );
@@ -162,7 +166,7 @@ impl Runner {
162 166
163 let permit = tokio::select! {167 let permit = tokio::select! {
164 _ = shutdown.cancelled() => break RunEnd::Stopped,168 _ = shutdown.cancelled() => break RunEnd::Stopped,
165- permit = semaphore.clone().acquire_owned() => match permit {169+ permit = self.limiter.acquire() => match permit {
166 Ok(permit) => permit,170 Ok(permit) => permit,
167 Err(_) => break RunEnd::Stopped,171 Err(_) => break RunEnd::Stopped,
168 },172 },
@@ -172,10 +176,16 @@ impl Runner {
172 drop(permit);176 drop(permit);
173 break RunEnd::Stopped;177 break RunEnd::Stopped;
174 }178 }
175- r = self.client.claim(&self.config.runner_secret, &self.config.labels) => r,179+ r = self.client.claim_with(
180+ &self.config.runner_secret,
181+ &self.config.labels,
182+ Some(self.limiter.current()),
183+ ) => r,
176 };184 };
177 match claimed {185 match claimed {
178 Ok(reply) => {186 Ok(reply) => {
187+ // No header means no override: back to the runner.toml value.
188+ self.limiter.apply_logged(reply.concurrency);
179 if updates.observe(reply.binary_sha256.as_deref())189 if updates.observe(reply.binary_sha256.as_deref())
180 && let Some(sha) = updates.pending()190 && let Some(sha) = updates.pending()
181 {191 {
@@ -353,6 +363,7 @@ impl Runner {
353 363
354 fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> {364 fn spawn_heartbeat(&self, job: &JobAssignment, cancel: CancellationToken) -> JoinHandle<()> {
355 let client = self.client.clone();365 let client = self.client.clone();
366+ let limiter = self.limiter.clone();
356 let job_id = job.job_id.clone();367 let job_id = job.job_id.clone();
357 let token = job.job_token.clone();368 let token = job.job_token.clone();
358 let every = self.options.heartbeat_every;369 let every = self.options.heartbeat_every;
@@ -360,13 +371,18 @@ impl Runner {
360 let mut ticker = tokio::time::interval_at(Instant::now() + every, every);371 let mut ticker = tokio::time::interval_at(Instant::now() + every, every);
361 loop {372 loop {
362 ticker.tick().await;373 ticker.tick().await;
363- match client.heartbeat(&job_id, &token).await {374+ match client
375+ .heartbeat_with(&job_id, &token, Some(limiter.current()))
376+ .await
377+ {
364 Ok(beat) if beat.cancel => {378 Ok(beat) if beat.cancel => {
379+ limiter.apply_logged(beat.concurrency);
365 tracing::info!(job_id = %job_id, "forge requested cancel");380 tracing::info!(job_id = %job_id, "forge requested cancel");
366 cancel.cancel();381 cancel.cancel();
367 return;382 return;
368 }383 }
369- Ok(_) => {}384+ // A runner at its limit does not claim, so the heartbeat carries changes too.
385+ Ok(beat) => limiter.apply_logged(beat.concurrency),
370 Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"),386 Err(e) => tracing::warn!(job_id = %job_id, error = %e, "heartbeat failed"),
371 }387 }
372 }388 }
crates/forge-runner/tests/flow.rsmodified+4 -1
@@ -127,7 +127,10 @@ fn route(
127 ("POST", ["heartbeat"]) => {127 ("POST", ["heartbeat"]) => {
128 st.heartbeats += 1;128 st.heartbeats += 1;
129 let cancel = st.cancel_from_heartbeat.is_some_and(|n| st.heartbeats >= n);129 let cancel = st.cancel_from_heartbeat.is_some_and(|n| st.heartbeats >= n);
130- Reply::json(&forge_ci::proto::HeartbeatResponse { cancel })130+ Reply::json(&forge_ci::proto::HeartbeatResponse {
131+ cancel,
132+ concurrency: None,
133+ })
131 }134 }
132 ("PUT", ["artifacts", name]) => {135 ("PUT", ["artifacts", name]) => {
133 let valid = !name.is_empty()136 let valid = !name.is_empty()
crates/forge-web/src/api/releases.rsmodified+1 -2
@@ -395,7 +395,6 @@ fn no_content() -> Response {
395 #[cfg(test)]395 #[cfg(test)]
396 mod tests {396 mod tests {
397 use std::path::{Path, PathBuf};397 use std::path::{Path, PathBuf};
398- use std::sync::Arc;
399 398
400 use forge_core::releases::NewRelease;399 use forge_core::releases::NewRelease;
401 use forge_core::token::{generate_token, hash_token};400 use forge_core::token::{generate_token, hash_token};
@@ -448,7 +447,7 @@ mod tests {
448 if let Some(mb) = max_mb {447 if let Some(mb) = max_mb {
449 let mut config = (*state.config).clone();448 let mut config = (*state.config).clone();
450 config.releases.max_asset_mb = mb;449 config.releases.max_asset_mb = mb;
451- state.config = Arc::new(config);450+ state.set_config(config);
452 }451 }
453 let store = state.store.clone();452 let store = state.store.clone();
454 let owner = store453 let owner = store
crates/forge-web/src/boot.rsmodified+27 -2
@@ -31,7 +31,13 @@ use crate::state::AppState;
31 pub(crate) const MIN_GIT: (u32, u32, u32) = (2, 38, 0);31 pub(crate) const MIN_GIT: (u32, u32, u32) = (2, 38, 0);
32 32
33 /// Boots every component and serves until shutdown.33 /// Boots every component and serves until shutdown.
34-pub async fn serve(config: Config) -> forge_core::Result<()> {34+pub async fn serve(
35+ file_config: Config,
36+ file_keys: std::collections::BTreeSet<String>,
37+) -> forge_core::Result<()> {
38+ // The listeners, the database path and the data dir are read-only settings, so the file alone
39+ // decides them. Every other field may be overridden in the database, which opens below.
40+ let config = file_config.clone();
35 let listen = config.listen;41 let listen = config.listen;
36 let user_content_listen = config.user_content_listen;42 let user_content_listen = config.user_content_listen;
37 let ssh_listen = config.ssh_listen;43 let ssh_listen = config.ssh_listen;
@@ -45,6 +51,24 @@ pub async fn serve(config: Config) -> forge_core::Result<()> {
45 let store = Store::open(&config.database).await?;51 let store = Store::open(&config.database).await?;
46 store.set_secret_key(*key);52 store.set_secret_key(*key);
47 53
54+ // Layer the stored admin overrides on the file config (UI, then file, then default). If the
55+ // two no longer validate together, boot with the file alone and say so.
56+ let overrides = store.server_overrides().await?;
57+ let (config, rejected) = forge_core::server_settings::boot_config(&config, &overrides);
58+ if let Some(e) = rejected {
59+ tracing::error!(error = %e, "stored server settings do not validate with the config file, ignoring them");
60+ }
61+ let file_config = Arc::new(file_config);
62+ let config = Arc::new(config);
63+ let settings = Arc::new(forge_core::server_settings::Live::new(
64+ file_config,
65+ file_keys,
66+ config.clone(),
67+ ));
68+ if let Err(e) = settings.publish(&overrides) {
69+ tracing::error!(error = %e, "stored live server settings were not applied");
70+ }
71+
48 let git = Arc::new(GitEnv {72 let git = Arc::new(GitEnv {
49 git_bin: find_git(),73 git_bin: find_git(),
50 data_dir: data_dir.clone(),74 data_dir: data_dir.clone(),
@@ -91,7 +115,8 @@ pub async fn serve(config: Config) -> forge_core::Result<()> {
91 };115 };
92 let blobs = crate::blobs::BlobStore::from_config(&config.storage, &data_dir)?;116 let blobs = crate::blobs::BlobStore::from_config(&config.storage, &data_dir)?;
93 let state = AppState {117 let state = AppState {
94- config: Arc::new(config),118+ config,
119+ settings,
95 store,120 store,
96 git,121 git,
97 key,122 key,
crates/forge-web/src/ci/api.rsmodified+136 -15
@@ -9,10 +9,11 @@
9 use forge_ci::config::JobSpec;9 use forge_ci::config::JobSpec;
10 use forge_ci::mask::Masker;10 use forge_ci::mask::Masker;
11 use forge_ci::proto::{11 use forge_ci::proto::{
12- FinishRequest, HeartbeatResponse, JobAssignment, Outcome, RegisterRequest, RegisterResponse,12+ CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse, JobAssignment, Outcome,
13+ RegisterRequest, RegisterResponse, RunnerConfigOverrides, RunnerConfigReport,
13 };14 };
14 use forge_core::Error as CoreError;15 use forge_core::Error as CoreError;
15-use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState};16+use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, RunState, RunnerReport};
16 use futures_util::StreamExt;17 use futures_util::StreamExt;
17 use http::header::HeaderValue;18 use http::header::HeaderValue;
18 use serde_json::json;19 use serde_json::json;
@@ -170,21 +171,109 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
170 }171 }
171 172
172 #[route(POST "/api/v1/ci/runners/claim")]173 #[route(POST "/api/v1/ci/runners/claim")]
173-async fn claim(cx: &Cx) -> topcoat::Result<Response> {174+async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
174- let mut res = claim_work(cx).await?;175+ let state = app_context::<AppState>(cx);
176+ // The labels in the request are ignored: the labels stored at registration are used.
177+ let runner = match runner_from(state, headers(cx)).await {
178+ Ok(runner) => runner,
179+ Err(res) => return Ok(*res),
180+ };
181+ // What the runner says about itself. An older runner sends only labels, and a body that does
182+ // not parse is not worth failing a claim over.
183+ let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await {
184+ Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
185+ Err(_) => ClaimRequest::default(),
186+ };
187+ note_report(
188+ state,
189+ &runner.id,
190+ &RunnerReport {
191+ concurrency: request.concurrency,
192+ version: request.version.filter(|v| v.len() <= 64),
193+ cpus: request.cpus,
194+ memory_bytes: request.memory_bytes,
195+ },
196+ )
197+ .await;
198+ let mut res = claim_work(state, &runner).await?;
199+ // The override can change during the long poll, so it is read at answer time.
200+ set_concurrency_header(state, &runner.id, &mut res).await;
175 // Advertises the binary sha256 when self-update is on and the runner asked for this target.201 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
176- self_update::advertise(app_context::<AppState>(cx), headers(cx), &mut res);202+ self_update::advertise(state, headers(cx), &mut res);
177 Ok(res)203 Ok(res)
178 }204 }
179 205
180-async fn claim_work(cx: &Cx) -> topcoat::Result<Response> {206+/// Stores a runner's self report and wakes the admin pages when it changed something.
207+async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {
208+ match state.store.record_runner_report(runner_id, report).await {
209+ Ok(true) => state.ci_live.bump_runners(),
210+ Ok(false) => {}
211+ Err(e) => tracing::warn!(error = %e, "ci: runner report not stored"),
212+ }
213+}
214+
215+/// Adds the admin's concurrency override to a claim answer. No header means no override.
216+async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) {
217+ if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
218+ return;
219+ }
220+ if let Ok(Some(n)) = state.store.runner_concurrency_override(runner_id).await
221+ && let Ok(value) = HeaderValue::from_str(&n.to_string())
222+ {
223+ res.headers_mut().insert(CONCURRENCY_HEADER, value);
224+ }
225+}
226+
227+/// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
228+/// starts, applies them to its in-memory config, then reports its effective config here.
229+#[route(GET "/api/v1/ci/runners/config")]
230+async fn runner_config_get(cx: &Cx) -> topcoat::Result<Response> {
181 let state = app_context::<AppState>(cx);231 let state = app_context::<AppState>(cx);
182- // The labels in the request are ignored: the labels stored at registration are used.
183 let runner = match runner_from(state, headers(cx)).await {232 let runner = match runner_from(state, headers(cx)).await {
184 Ok(runner) => runner,233 Ok(runner) => runner,
185 Err(res) => return Ok(*res),234 Err(res) => return Ok(*res),
186 };235 };
236+ Ok(overrides_response(&runner))
237+}
187 238
239+#[route(PUT "/api/v1/ci/runners/config")]
240+async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result<Response> {
241+ let state = app_context::<AppState>(cx);
242+ let runner = match runner_from(state, headers(cx)).await {
243+ Ok(runner) => runner,
244+ Err(res) => return Ok(*res),
245+ };
246+ let report: RunnerConfigReport = match json_body(body).await {
247+ Ok(report) => report,
248+ Err(res) => return Ok(*res),
249+ };
250+ // Only known fields are kept, and the secret is never stored whatever the runner sent.
251+ let mut config = report.config;
252+ config.retain(|key, _| forge_core::ci::runner_field(key).is_some());
253+ config.insert("runner_secret".into(), json!("<redacted>"));
254+ match state
255+ .store
256+ .set_runner_reported_config(&runner.id, &config)
257+ .await
258+ {
259+ Ok(true) => state.ci_live.bump_runners(),
260+ Ok(false) => {}
261+ Err(e) => return Ok(*api::internal(e)),
262+ }
263+ Ok(overrides_response(&runner))
264+}
265+
266+fn overrides_response(runner: &CiRunner) -> Response {
267+ let reply = RunnerConfigOverrides {
268+ overrides: runner.config_overrides.clone(),
269+ };
270+ api::json(
271+ StatusCode::OK,
272+ &serde_json::to_value(reply).unwrap_or_default(),
273+ )
274+}
275+
276+async fn claim_work(state: &AppState, runner: &CiRunner) -> topcoat::Result<Response> {
188 // Arm the wake-up before each attempt, so a job queued during the attempt is not missed.277 // Arm the wake-up before each attempt, so a job queued during the attempt is not missed.
189 // Producers use notify_waiters, which wakes every claimer, so a runner whose labels278 // Producers use notify_waiters, which wakes every claimer, so a runner whose labels
190 // don't match a job re-arms and keeps waiting for the rest of CLAIM_WAIT.279 // 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<Response> {
194 let mut woken = std::pin::pin!(waker.notified());283 let mut woken = std::pin::pin!(waker.notified());
195 woken.as_mut().enable();284 woken.as_mut().enable();
196 285
197- match try_claim(state, &runner).await {286+ match try_claim(state, runner).await {
198 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),287 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),
199 Ok(None) => {}288 Ok(None) => {}
200 Err(res) => return Ok(*res),289 Err(res) => return Ok(*res),
@@ -252,6 +341,7 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssi
252 state.ci_live.bump_job(&job.id);341 state.ci_live.bump_job(&job.id);
253 state.ci_live.bump_run(&run.id);342 state.ci_live.bump_run(&run.id);
254 state.ci_live.bump_repo(&run.repo_id);343 state.ci_live.bump_repo(&run.repo_id);
344+ state.ci_live.bump_runners();
255 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;345 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
256 let repo = state346 let repo = state
257 .store347 .store
@@ -411,10 +501,40 @@ async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
411 Err(res) => return Ok(*res),501 Err(res) => return Ok(*res),
412 };502 };
413 match state.store.heartbeat(&job.id).await {503 match state.store.heartbeat(&job.id).await {
414- Ok(cancel) => Ok(api::json(504+ Ok(cancel) => {
415- StatusCode::OK,505+ // The runner says its live concurrency, and the answer carries the admin's override.
416- &serde_json::to_value(HeartbeatResponse { cancel }).unwrap_or_default(),506+ // A runner at its limit does not claim, so this is how it learns about a change.
417- )),507+ let mut concurrency = None;
508+ if let Some(runner_id) = job.runner_id.as_deref() {
509+ let said = headers(cx)
510+ .get(CONCURRENCY_HEADER)
511+ .and_then(|v| v.to_str().ok())
512+ .and_then(|v| v.trim().parse::<u32>().ok());
513+ note_report(
514+ state,
515+ runner_id,
516+ &RunnerReport {
517+ concurrency: said,
518+ ..RunnerReport::default()
519+ },
520+ )
521+ .await;
522+ concurrency = state
523+ .store
524+ .runner_concurrency_override(runner_id)
525+ .await
526+ .ok()
527+ .flatten();
528+ }
529+ Ok(api::json(
530+ StatusCode::OK,
531+ &serde_json::to_value(HeartbeatResponse {
532+ cancel,
533+ concurrency,
534+ })
535+ .unwrap_or_default(),
536+ ))
537+ }
418 Err(e) => Ok(*api::internal(e)),538 Err(e) => Ok(*api::internal(e)),
419 }539 }
420 }540 }
@@ -557,7 +677,7 @@ async fn store_log_bytes(
557 ) -> Result<(), Refusal> {677 ) -> Result<(), Refusal> {
558 use tokio::io::AsyncWriteExt;678 use tokio::io::AsyncWriteExt;
559 679
560- let cap = state.config.ci.max_log_mb.saturating_mul(MIB);680+ let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
561 let current = match tokio::fs::metadata(path).await {681 let current = match tokio::fs::metadata(path).await {
562 Ok(meta) => meta.len(),682 Ok(meta) => meta.len(),
563 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,683 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
@@ -610,7 +730,7 @@ async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
610 /// Streams the body to a temporary blob, then records the artifact and moves the blob to its730 /// Streams the body to a temporary blob, then records the artifact and moves the blob to its
611 /// final key `ci/<artifact id>`. The id is only known once the row exists.731 /// final key `ci/<artifact id>`. The id is only known once the row exists.
612 async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result<String, Refusal> {732 async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result<String, Refusal> {
613- let max_artifacts = state.config.ci.max_artifacts_per_job;733+ let max_artifacts = state.live().ci.max_artifacts_per_job;
614 let existing = state734 let existing = state
615 .store735 .store
616 .list_artifacts(&job.id)736 .list_artifacts(&job.id)
@@ -629,7 +749,7 @@ async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result
629 )));749 )));
630 }750 }
631 751
632- let max_bytes = state.config.ci.max_artifact_mb.saturating_mul(MIB);752+ let max_bytes = state.live().ci.max_artifact_mb.saturating_mul(MIB);
633 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());753 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());
634 let mut writer = state754 let mut writer = state
635 .blobs755 .blobs
@@ -770,6 +890,7 @@ async fn finish_job(
770 crate::ci::sync_status(state, &run, &other).await;890 crate::ci::sync_status(state, &run, &other).await;
771 }891 }
772 }892 }
893+ state.ci_live.bump_runners();
773 if any_changed {894 if any_changed {
774 state.ci_live.bump_run(&run.id);895 state.ci_live.bump_run(&run.id);
775 state.ci_live.bump_repo(&run.repo_id);896 state.ci_live.bump_repo(&run.repo_id);
crates/forge-web/src/ci/api_tests.rsmodified+104 -3
@@ -2,7 +2,6 @@
2 //! server builds, so routing, auth and status codes are covered end to end.2 //! server builds, so routing, auth and status codes are covered end to end.
3 3
4 use std::path::PathBuf;4 use std::path::PathBuf;
5-use std::sync::Arc;
6 5
7 use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob};6 use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, NewJob};
8 use forge_core::{Repo, Store, Visibility};7 use forge_core::{Repo, Store, Visibility};
@@ -79,7 +78,7 @@ async fn bare(tune: impl FnOnce(&mut forge_core::config::CiConfig)) -> Bare {
79 let mut state = test_state(&data_dir).await;78 let mut state = test_state(&data_dir).await;
80 let mut config = (*state.config).clone();79 let mut config = (*state.config).clone();
81 tune(&mut config.ci);80 tune(&mut config.ci);
82- state.config = Arc::new(config);81+ state.set_config(config);
83 let store = state.store.clone();82 let store = state.store.clone();
84 let router = app_router(state);83 let router = app_router(state);
85 let owner = store84 let owner = store
@@ -462,6 +461,108 @@ async fn heartbeat_reports_a_cancel_request() {
462 assert_eq!(sent.status, 401);461 assert_eq!(sent.status, 401);
463 }462 }
464 463
464+#[tokio::test]
465+async fn claim_and_heartbeat_carry_the_concurrency_round_trip() {
466+ let env = bare(|_| {}).await;
467+ let (runner, secret) = runner(&env, &[]).await;
468+ make_run(&env, "push", None, COMMIT, &[job("a", spec(&[], &[]))]).await;
469+ make_run(&env, "push", None, COMMIT, &[job("b", spec(&[], &[]))]).await;
470+
471+ // No override: no header, and the runner's report is stored.
472+ let body = serde_json::json!({
473+ "labels": [], "concurrency": 2, "version": "9.9.9", "cpus": 8, "memory_bytes": 17179869184u64
474+ });
475+ let sent = send(
476+ &env.router,
477+ "POST",
478+ "/api/v1/ci/runners/claim",
479+ &[bearer(&secret)],
480+ json_body(&body),
481+ )
482+ .await;
483+ assert_eq!(sent.status, 200);
484+ assert!(sent.headers.get("Forge-Runner-Concurrency").is_none());
485+ let listed = env.store.list_runners().await.unwrap().remove(0);
486+ assert_eq!(listed.reported.concurrency, Some(2));
487+ assert_eq!(listed.reported.version.as_deref(), Some("9.9.9"));
488+ assert_eq!(listed.reported.cpus, Some(8));
489+ assert_eq!(listed.running_jobs, 1);
490+ let assignment = sent.json();
491+
492+ // An override set in the UI shows up on the next claim answer and on the heartbeat.
493+ env.store
494+ .set_runner_concurrency(&runner.id, Some(4))
495+ .await
496+ .unwrap();
497+ let sent = claim(&env.router, &secret).await;
498+ assert_eq!(sent.status, 200);
499+ assert_eq!(sent.headers.get("Forge-Runner-Concurrency").unwrap(), "4");
500+ let uri = format!(
501+ "/api/v1/ci/jobs/{}/heartbeat",
502+ assignment["job_id"].as_str().unwrap()
503+ );
504+ let token = assignment["job_token"].as_str().unwrap();
505+ let beat = send(
506+ &env.router,
507+ "POST",
508+ &uri,
509+ &[bearer(token), ("Forge-Runner-Concurrency", "3".to_owned())],
510+ Vec::new(),
511+ )
512+ .await;
513+ assert_eq!(beat.json()["concurrency"], 4);
514+ assert_eq!(
515+ env.store.list_runners().await.unwrap()[0]
516+ .reported
517+ .concurrency,
518+ Some(3),
519+ "the heartbeat reports the live value"
520+ );
521+
522+ // Cleared: the heartbeat omits the field, so an old runner sees the same body as before.
523+ env.store
524+ .set_runner_concurrency(&runner.id, None)
525+ .await
526+ .unwrap();
527+ let beat = send(&env.router, "POST", &uri, &[bearer(token)], Vec::new()).await;
528+ assert!(beat.json().get("concurrency").is_none());
529+}
530+
531+#[tokio::test]
532+async fn runner_config_report_and_overrides_round_trip() {
533+ let env = bare(|_| {}).await;
534+ let (runner, secret) = runner(&env, &["linux"]).await;
535+ let uri = "/api/v1/ci/runners/config";
536+ let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await;
537+ assert_eq!(sent.status, 200);
538+ assert_eq!(sent.json()["overrides"], serde_json::json!({}));
539+
540+ env.store
541+ .set_runner_field(&runner.id, "limits.memory", Some("8g"))
542+ .await
543+ .unwrap();
544+ let report = serde_json::json!({ "config": {
545+ "limits.memory": "4g", "runner_secret": "leaked", "bogus.key": 1, "concurrency": 1
546+ }});
547+ let sent = send(
548+ &env.router,
549+ "PUT",
550+ uri,
551+ &[bearer(&secret)],
552+ json_body(&report),
553+ )
554+ .await;
555+ assert_eq!(sent.status, 200);
556+ assert_eq!(sent.json()["overrides"]["limits.memory"], "8g");
557+ let stored = env.store.list_runners().await.unwrap().remove(0);
558+ assert_eq!(stored.reported_config["limits.memory"], "4g");
559+ assert_eq!(stored.reported_config["runner_secret"], "<redacted>");
560+ assert!(!stored.reported_config.contains_key("bogus.key"));
561+
562+ let sent = send(&env.router, "GET", uri, &[bearer("wrong")], Vec::new()).await;
563+ assert_eq!(sent.status, 401);
564+}
565+
465 // ---------------------------------------------------------------------------------------------566 // ---------------------------------------------------------------------------------------------
466 // Artifacts567 // Artifacts
467 // ---------------------------------------------------------------------------------------------568 // ---------------------------------------------------------------------------------------------
@@ -852,7 +953,7 @@ async fn bare_with_self_update() -> Bare {
852 let mut config = (*state.config).clone();953 let mut config = (*state.config).clone();
853 config.self_update.enabled = true;954 config.self_update.enabled = true;
854 config.self_update.repo = format!("{OWNER}/{REPO}");955 config.self_update.repo = format!("{OWNER}/{REPO}");
855- state.config = Arc::new(config);956+ state.set_config(config);
856 let store = state.store.clone();957 let store = state.store.clone();
857 let router = app_router(state);958 let router = app_router(state);
858 let owner = store959 let owner = store
crates/forge-web/src/ci/live.rsmodified+15 -0
@@ -12,12 +12,16 @@ use std::sync::{Mutex, MutexGuard, PoisonError};
12 12
13 use tokio::sync::watch;13 use tokio::sync::watch;
14 14
15+/// The one key of the runners signal: the admin pages follow all runners together.
16+const RUNNERS_KEY: &str = "runners";
17+
15 /// The change counters of CI jobs and runs, each keyed by its id.18 /// The change counters of CI jobs and runs, each keyed by its id.
16 #[derive(Default)]19 #[derive(Default)]
17 pub struct CiLive {20 pub struct CiLive {
18 jobs: Signals,21 jobs: Signals,
19 runs: Signals,22 runs: Signals,
20 repos: Signals,23 repos: Signals,
24+ runners: Signals,
21 }25 }
22 26
23 impl CiLive {27 impl CiLive {
@@ -38,6 +42,17 @@ impl CiLive {
38 self.repos.subscribe(repo_id)42 self.repos.subscribe(repo_id)
39 }43 }
40 44
45+ /// Subscribes to changes of any runner: its jobs, live concurrency, reported config or an
46+ /// admin edit. Same rules as [`CiLive::subscribe_job`].
47+ pub fn subscribe_runners(&self) -> watch::Receiver<u64> {
48+ self.runners.subscribe(RUNNERS_KEY)
49+ }
50+
51+ /// Wakes the subscribers of the runners pages.
52+ pub fn bump_runners(&self) {
53+ self.runners.bump(RUNNERS_KEY);
54+ }
55+
41 /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when56 /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when
42 /// nobody is subscribed.57 /// nobody is subscribed.
43 pub fn bump_job(&self, job_id: &str) {58 pub fn bump_job(&self, job_id: &str) {
crates/forge-web/src/ci/reaper.rsmodified+3 -1
@@ -81,6 +81,7 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize {
81 state.ci_waker.notify_waiters();81 state.ci_waker.notify_waiters();
82 }82 }
83 if !jobs.is_empty() {83 if !jobs.is_empty() {
84+ state.ci_live.bump_runners();
84 tracing::warn!(count = jobs.len(), "ci: reaped lost jobs");85 tracing::warn!(count = jobs.len(), "ci: reaped lost jobs");
85 }86 }
86 jobs.len()87 jobs.len()
@@ -89,7 +90,8 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize {
89 /// Deletes the logs and artifacts past retention. Rows go first (in the store); files follow.90 /// Deletes the logs and artifacts past retention. Rows go first (in the store); files follow.
90 /// Missing files are fine. Returns `(logs deleted, artifacts deleted)` as attempted.91 /// Missing files are fine. Returns `(logs deleted, artifacts deleted)` as attempted.
91 pub async fn purge_once(state: &AppState) -> (usize, usize) {92 pub async fn purge_once(state: &AppState) -> (usize, usize) {
92- let ci = &state.config.ci;93+ let live = state.live();
94+ let ci = &live.ci;
93 let day = |days: u64| Duration::from_secs(days.saturating_mul(24 * 60 * 60));95 let day = |days: u64| Duration::from_secs(days.saturating_mul(24 * 60 * 60));
94 let logs_before = stamp_ago(day(ci.log_retention_days));96 let logs_before = stamp_ago(day(ci.log_retention_days));
95 let artifacts_before = stamp_ago(day(ci.artifact_retention_days));97 let artifacts_before = stamp_ago(day(ci.artifact_retention_days));
crates/forge-web/src/ci/release.rsmodified+2 -2
@@ -96,7 +96,7 @@ async fn publish(
96 return format!("Could not publish release {tag}: could not list the jobs");96 return format!("Could not publish release {tag}: could not list the jobs");
97 }97 }
98 };98 };
99- let max_bytes = state.config.releases.max_asset_mb.saturating_mul(MIB);99+ let max_bytes = state.live().releases.max_asset_mb.saturating_mul(MIB);
100 let mut attached = 0usize;100 let mut attached = 0usize;
101 let mut failed: Vec<String> = Vec::new();101 let mut failed: Vec<String> = Vec::new();
102 for job in &jobs {102 for job in &jobs {
@@ -329,7 +329,7 @@ fn bullets(commits: &[CommitInfo], footer: Option<&str>) -> String {
329 /// the outcome is not lost, it is also in the tracing output.329 /// the outcome is not lost, it is also in the tracing output.
330 async fn note(state: &AppState, job: &CiJob, text: &str) {330 async fn note(state: &AppState, job: &CiJob, text: &str) {
331 let line = format!("[forge] {text}\n");331 let line = format!("[forge] {text}\n");
332- let cap = state.config.ci.max_log_mb.saturating_mul(MIB);332+ let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
333 let path = log_path(&state.config.data_dir, &job.id);333 let path = log_path(&state.config.data_dir, &job.id);
334 let current = match tokio::fs::metadata(&path).await {334 let current = match tokio::fs::metadata(&path).await {
335 Ok(meta) => meta.len(),335 Ok(meta) => meta.len(),
crates/forge-web/src/ci/schedule.rsmodified+5 -6
@@ -71,7 +71,7 @@ pub async fn on_ref_update(
71 refname: &str,71 refname: &str,
72 new_oid: &str,72 new_oid: &str,
73 ) {73 ) {
74- if !state.config.ci.enabled || is_zero_oid(new_oid) {74+ if !state.live().ci.enabled || is_zero_oid(new_oid) {
75 return;75 return;
76 }76 }
77 let (trigger, event) = if let Some(branch) = refname.strip_prefix("refs/heads/") {77 let (trigger, event) = if let Some(branch) = refname.strip_prefix("refs/heads/") {
@@ -118,7 +118,7 @@ pub async fn on_ref_update(
118 /// the head commit. A fork head, or an author without Write on the base repo, creates the run in118 /// the head commit. A fork head, or an author without Write on the base repo, creates the run in
119 /// WaitingApproval: its jobs wait until someone approves it.119 /// WaitingApproval: its jobs wait until someone approves it.
120 pub async fn on_pull_event(state: &AppState, repo: &Repo, pull: &PullRequest, actor_id: &str) {120 pub async fn on_pull_event(state: &AppState, repo: &Repo, pull: &PullRequest, actor_id: &str) {
121- if !state.config.ci.enabled {121+ if !state.live().ci.enabled {
122 return;122 return;
123 }123 }
124 if let Err(e) = pull_run(state, repo, pull, actor_id).await {124 if let Err(e) = pull_run(state, repo, pull, actor_id).await {
@@ -171,7 +171,7 @@ pub async fn manual_run(
171 branch: &str,171 branch: &str,
172 actor_id: &str,172 actor_id: &str,
173 ) -> forge_core::Result<CiRun> {173 ) -> forge_core::Result<CiRun> {
174- if !state.config.ci.enabled {174+ if !state.live().ci.enabled {
175 return Err(forge_core::Error::Invalid(175 return Err(forge_core::Error::Invalid(
176 "CI is disabled on this instance".into(),176 "CI is disabled on this instance".into(),
177 ));177 ));
@@ -293,7 +293,7 @@ async fn note_warnings(
293 for warning in warnings.iter().take(MAX_WARNING_LINES) {293 for warning in warnings.iter().take(MAX_WARNING_LINES) {
294 text.push_str(&format!("[forge] warning: {warning}\n"));294 text.push_str(&format!("[forge] warning: {warning}\n"));
295 }295 }
296- let cap = state.config.ci.max_log_mb.saturating_mul(MIB);296+ let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
297 for job in state.store.jobs_for_run(&run.id).await? {297 for job in state.store.jobs_for_run(&run.id).await? {
298 let path = log_path(&state.config.data_dir, &job.id);298 let path = log_path(&state.config.data_dir, &job.id);
299 let current = match tokio::fs::metadata(&path).await {299 let current = match tokio::fs::metadata(&path).await {
@@ -466,7 +466,6 @@ where
466 #[cfg(test)]466 #[cfg(test)]
467 pub(super) mod tests {467 pub(super) mod tests {
468 use std::path::{Path, PathBuf};468 use std::path::{Path, PathBuf};
469- use std::sync::Arc;
470 use std::time::Duration;469 use std::time::Duration;
471 470
472 use forge_core::ci::{CiJob, CiRunner, JobState, RunState};471 use forge_core::ci::{CiJob, CiRunner, JobState, RunState};
@@ -1020,7 +1019,7 @@ run = "make"
1020 let mut cfg = (*fx.state.config).clone();1019 let mut cfg = (*fx.state.config).clone();
1021 cfg.ci.log_retention_days = 0;1020 cfg.ci.log_retention_days = 0;
1022 let mut state = fx.state.clone();1021 let mut state = fx.state.clone();
1023- state.config = Arc::new(cfg);1022+ state.set_config(cfg);
1024 tokio::time::sleep(Duration::from_millis(1100)).await;1023 tokio::time::sleep(Duration::from_millis(1100)).await;
1025 1024
1026 let (logs, _artifacts) = purge_once(&state).await;1025 let (logs, _artifacts) = purge_once(&state).await;
crates/forge-web/src/client_ip.rsmodified+2 -1
@@ -18,7 +18,8 @@ const FORWARDED_FOR: &str = "x-forwarded-for";
18 /// The client IP for this request, bucketed for throttling. Unix-socket requests have no peer and18 /// The client IP for this request, bucketed for throttling. Unix-socket requests have no peer and
19 /// map to the unspecified address.19 /// map to the unspecified address.
20 pub fn client_ip(cx: &Cx) -> IpAddr {20 pub fn client_ip(cx: &Cx) -> IpAddr {
21- let trusted = &app_context::<AppState>(cx).config.trusted_proxies;21+ let live = app_context::<AppState>(cx).live();
22+ let trusted = &live.trusted_proxies;
22 let peer = remote_addr(cx).map(|addr| addr.ip());23 let peer = remote_addr(cx).map(|addr| addr.ip());
23 let forwarded = headers(cx)24 let forwarded = headers(cx)
24 .get_all(FORWARDED_FOR)25 .get_all(FORWARDED_FOR)
crates/forge-web/src/i18n/admin.rsmodified+96 -0
@@ -66,6 +66,29 @@ pub enum K {
66 LastDbSnapshotShipped,66 LastDbSnapshotShipped,
67 LastSeen,67 LastSeen,
68 LastSuccess,68 LastSuccess,
69+ ServerSettings,
70+ ServerSettingsIntro,
71+ SrvTabGeneral,
72+ SrvTabLimits,
73+ SrvTabStorage,
74+ SrvTabBackups,
75+ SrvTabIntegrations,
76+ SrvSaved,
77+ SrvNothingChanged,
78+ SrvResetDone,
79+ SrvResetToFile,
80+ SrvRestartNeeded,
81+ SrvKindLive,
82+ SrvKindRestart,
83+ SrvKindReadOnly,
84+ SrvSourceDefault,
85+ SrvSourceFile,
86+ SrvSourceUi,
87+ SrvSecretSet,
88+ SrvSecretNotSet,
89+ SrvSecretHint,
90+ SrvFileValue,
91+ SrvEmpty,
69 Mail,92 Mail,
70 MailHost,93 MailHost,
71 MailIntro,94 MailIntro,
@@ -305,6 +328,56 @@ pub fn t(lang: Lang, key: K) -> &'static str {
305 (LastSeen, Tr) => "Son görülme",328 (LastSeen, Tr) => "Son görülme",
306 (LastSuccess, En) => "Last success",329 (LastSuccess, En) => "Last success",
307 (LastSuccess, Tr) => "Son başarı",330 (LastSuccess, Tr) => "Son başarı",
331+ (ServerSettings, En) => "Server",
332+ (ServerSettings, Tr) => "Sunucu",
333+ (ServerSettingsIntro, En) => {
334+ "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."
335+ }
336+ (ServerSettingsIntro, Tr) => {
337+ "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."
338+ }
339+ (SrvTabGeneral, En) => "General",
340+ (SrvTabGeneral, Tr) => "Genel",
341+ (SrvTabLimits, En) => "CI and limits",
342+ (SrvTabLimits, Tr) => "CI ve sınırlar",
343+ (SrvTabStorage, En) => "Storage",
344+ (SrvTabStorage, Tr) => "Depolama",
345+ (SrvTabBackups, En) => "Backups",
346+ (SrvTabBackups, Tr) => "Yedekler",
347+ (SrvTabIntegrations, En) => "Integrations",
348+ (SrvTabIntegrations, Tr) => "Entegrasyonlar",
349+ (SrvSaved, En) => "Server settings saved.",
350+ (SrvSaved, Tr) => "Sunucu ayarları kaydedildi.",
351+ (SrvNothingChanged, En) => "Nothing changed.",
352+ (SrvNothingChanged, Tr) => "Değişiklik yok.",
353+ (SrvResetDone, En) => "Back to the file value.",
354+ (SrvResetDone, Tr) => "Dosya değerine dönüldü.",
355+ (SrvResetToFile, En) => "Reset to file value",
356+ (SrvResetToFile, Tr) => "Dosya değerine sıfırla",
357+ (SrvRestartNeeded, En) => "restart needed",
358+ (SrvRestartNeeded, Tr) => "yeniden başlatma gerekli",
359+ (SrvKindLive, En) => "live",
360+ (SrvKindLive, Tr) => "canlı",
361+ (SrvKindRestart, En) => "restart",
362+ (SrvKindRestart, Tr) => "yeniden başlatma",
363+ (SrvKindReadOnly, En) => "read-only",
364+ (SrvKindReadOnly, Tr) => "salt okunur",
365+ (SrvSourceDefault, En) => "default",
366+ (SrvSourceDefault, Tr) => "varsayılan",
367+ (SrvSourceFile, En) => "file",
368+ (SrvSourceFile, Tr) => "dosya",
369+ (SrvSourceUi, En) => "UI",
370+ (SrvSourceUi, Tr) => "arayüz",
371+ (SrvSecretSet, En) => "set",
372+ (SrvSecretSet, Tr) => "ayarlı",
373+ (SrvSecretNotSet, En) => "not set",
374+ (SrvSecretNotSet, Tr) => "ayarlı değil",
375+ (SrvSecretHint, En) => "Write-only. Leave blank to keep the current value.",
376+ (SrvSecretHint, Tr) => "Yalnızca yazılır. Mevcut değeri korumak için boş bırakın.",
377+ (SrvFileValue, En) => "File value",
378+ (SrvFileValue, Tr) => "Dosya değeri",
379+ (SrvEmpty, En) => "(empty)",
380+ (SrvEmpty, Tr) => "(boş)",
308 (Mail, En) => "Mail",381 (Mail, En) => "Mail",
309 (Mail, Tr) => "E-posta",382 (Mail, Tr) => "E-posta",
310 (MailTabSettings, En) => "Settings",383 (MailTabSettings, En) => "Settings",
@@ -782,6 +855,29 @@ mod tests {
782 K::LastDbSnapshotShipped,855 K::LastDbSnapshotShipped,
783 K::LastSeen,856 K::LastSeen,
784 K::LastSuccess,857 K::LastSuccess,
858+ K::ServerSettings,
859+ K::ServerSettingsIntro,
860+ K::SrvTabGeneral,
861+ K::SrvTabLimits,
862+ K::SrvTabStorage,
863+ K::SrvTabBackups,
864+ K::SrvTabIntegrations,
865+ K::SrvSaved,
866+ K::SrvNothingChanged,
867+ K::SrvResetDone,
868+ K::SrvResetToFile,
869+ K::SrvRestartNeeded,
870+ K::SrvKindLive,
871+ K::SrvKindRestart,
872+ K::SrvKindReadOnly,
873+ K::SrvSourceDefault,
874+ K::SrvSourceFile,
875+ K::SrvSourceUi,
876+ K::SrvSecretSet,
877+ K::SrvSecretNotSet,
878+ K::SrvSecretHint,
879+ K::SrvFileValue,
880+ K::SrvEmpty,
785 K::Mail,881 K::Mail,
786 K::MailHost,882 K::MailHost,
787 K::MailIntro,883 K::MailIntro,
crates/forge-web/src/lfs/route_tests.rsmodified+1 -2
@@ -1,7 +1,6 @@
1 //! Route tests for the LFS API, driven through the public router.1 //! Route tests for the LFS API, driven through the public router.
2 2
3 use std::path::PathBuf;3 use std::path::PathBuf;
4-use std::sync::Arc;
5 4
6 use base64::prelude::{BASE64_STANDARD, Engine};5 use base64::prelude::{BASE64_STANDARD, Engine};
7 use forge_core::lfs_token::{self, LfsOp};6 use forge_core::lfs_token::{self, LfsOp};
@@ -64,7 +63,7 @@ impl Fixture {
64 state.store = self.store.clone();63 state.store = self.store.clone();
65 let mut config = (*state.config).clone();64 let mut config = (*state.config).clone();
66 config.lfs.max_object_mb = max_object_mb;65 config.lfs.max_object_mb = max_object_mb;
67- state.config = Arc::new(config);66+ state.set_config(config);
68 self.router = app_router(state);67 self.router = app_router(state);
69 }68 }
70 }69 }
crates/forge-web/src/lfs/routes.rsmodified+2 -2
@@ -84,7 +84,7 @@ async fn batch(cx: &Cx, body: Body) -> topcoat::Result<Response> {
84 Ok(plan) => plan,84 Ok(plan) => plan,
85 Err(response) => return Ok(*response),85 Err(response) => return Ok(*response),
86 };86 };
87- let max = state.config.lfs.max_object_bytes();87+ let max = state.live().lfs.max_object_bytes();
88 for object in &request.objects {88 for object in &request.objects {
89 if !is_valid_oid(&object.oid) {89 if !is_valid_oid(&object.oid) {
90 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));90 return Ok(message(StatusCode::UNPROCESSABLE_ENTITY, "invalid oid"));
@@ -251,7 +251,7 @@ async fn put_object(cx: &Cx, body: Body) -> topcoat::Result<Response> {
251 return Ok(*response);251 return Ok(*response);
252 }252 }
253 253
254- let max = state.config.lfs.max_object_bytes();254+ let max = state.live().lfs.max_object_bytes();
255 let declared = headers255 let declared = headers
256 .get(CONTENT_LENGTH)256 .get(CONTENT_LENGTH)
257 .and_then(|v| v.to_str().ok())257 .and_then(|v| v.to_str().ok())
crates/forge-web/src/main.rsmodified+2 -2
@@ -71,8 +71,8 @@ async fn healthz() -> Result<String, topcoat::Error> {
71 }71 }
72 72
73 async fn serve(config_path: &std::path::Path) -> Result<(), BoxError> {73 async fn serve(config_path: &std::path::Path) -> Result<(), BoxError> {
74- let config = Config::load(config_path)?;74+ let (config, file_keys) = Config::load_with_keys(config_path)?;
75- boot::serve(config).await?;75+ boot::serve(config, file_keys).await?;
76 Ok(())76 Ok(())
77 }77 }
78 78
crates/forge-web/src/pages/admin_runners.rsmodified+597 -4
@@ -7,7 +7,7 @@
7 //! runner are audited; the token itself is never written to the audit log.7 //! runner are audited; the token itself is never written to the audit log.
8 8
9 use forge_core::AuditAction;9 use forge_core::AuditAction;
10-use forge_core::ci::CiRunner;10+use forge_core::ci::{CiRunner, FieldKind, RUNNER_FIELDS, runner_field};
11 use serde::Deserialize;11 use serde::Deserialize;
12 use time::OffsetDateTime;12 use time::OffsetDateTime;
13 use time::format_description::well_known::Rfc3339;13 use time::format_description::well_known::Rfc3339;
@@ -16,6 +16,7 @@ use topcoat::context::{Cx, app_context};
16 use topcoat::router::content::Form;16 use topcoat::router::content::Form;
17 use topcoat::router::error::{SeeOther, forbidden, see_other};17 use topcoat::router::error::{SeeOther, forbidden, see_other};
18 use topcoat::router::request::uri;18 use topcoat::router::request::uri;
19+use topcoat::router::response::Response;
19 use topcoat::router::{page, path_param, route};20 use topcoat::router::{page, path_param, route};
20 use topcoat::view::{View, component, view};21 use topcoat::view::{View, component, view};
21 22
@@ -24,12 +25,55 @@ use crate::auth::check_csrf;
24 use crate::i18n::admin::{self as g, K};25 use crate::i18n::admin::{self as g, K};
25 use crate::i18n::{self, Key, Lang};26 use crate::i18n::{self, Key, Lang};
26 use crate::pages::admin_users::admin_only;27 use crate::pages::admin_users::admin_only;
28+use crate::pages::ci_runs::events_response;
27 use crate::pages::repo_mirrors::stamp_in_tz;29 use crate::pages::repo_mirrors::stamp_in_tz;
28 use crate::state::AppState;30 use crate::state::AppState;
29 use crate::views::{enc, now_unix, relative_time, shell};31 use crate::views::{enc, now_unix, relative_time, shell};
30 32
31 path_param!(runner_id);33 path_param!(runner_id);
32 34
35+/// Picks the English or Turkish text. The runner page strings live here, not in `i18n::admin`.
36+fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
37+ match lang {
38+ Lang::En => en,
39+ Lang::Tr => tr,
40+ }
41+}
42+
43+/// Extra notice words: (word, English, Turkish, is an error).
44+const EXTRA_NOTICES: [(&str, &str, &str, bool); 5] = [
45+ (
46+ "saved",
47+ "Saved. The runner picks it up on its next check-in.",
48+ "Kaydedildi. Çalıştırıcı bir sonraki yoklamasında uygular.",
49+ false,
50+ ),
51+ (
52+ "saved-restart",
53+ "Saved. It applies when the runner next starts.",
54+ "Kaydedildi. Çalıştırıcı yeniden başlayınca uygulanır.",
55+ false,
56+ ),
57+ (
58+ "reset",
59+ "Override removed. The runner.toml value is used again.",
60+ "Üzerine yazma kaldırıldı. runner.toml değeri yeniden kullanılıyor.",
61+ false,
62+ ),
63+ (
64+ "invalid",
65+ "That value is not valid for this field. Nothing was changed.",
66+ "Bu değer bu alan için geçerli değil. Hiçbir şey değiştirilmedi.",
67+ true,
68+ ),
69+ (
70+ "read-only",
71+ "That field cannot be changed from the forge.",
72+ "Bu alan forge üzerinden değiştirilemez.",
73+ true,
74+ ),
75+];
76+
33 /// Notice words (the only text a `?notice=` query can show), their text key, and whether they are errors.77 /// Notice words (the only text a `?notice=` query can show), their text key, and whether they are errors.
34 const NOTICES: [(&str, K, bool); 5] = [78 const NOTICES: [(&str, K, bool); 5] = [
35 ("disabled", K::RunnerDisabledNotice, false),79 ("disabled", K::RunnerDisabledNotice, false),
@@ -45,6 +89,22 @@ struct CsrfForm {
45 csrf: String,89 csrf: String,
46 }90 }
47 91
92+#[derive(Deserialize)]
93+struct ConfigForm {
94+ #[serde(default)]
95+ csrf: String,
96+ #[serde(default)]
97+ key: String,
98+ #[serde(default)]
99+ value: String,
100+ /// Set by the "use runner.toml value" button.
101+ #[serde(default)]
102+ reset: String,
103+ /// `detail` returns to the runner's page, anything else to the list.
104+ #[serde(default)]
105+ back: String,
106+}
107+
48 #[derive(Deserialize)]108 #[derive(Deserialize)]
49 struct DisableForm {109 struct DisableForm {
50 #[serde(default)]110 #[serde(default)]
@@ -64,6 +124,36 @@ struct RunnerRow {
64 disabled: bool,124 disabled: bool,
65 toggle_action: String,125 toggle_action: String,
66 delete_action: String,126 delete_action: String,
127+ detail_href: String,
128+ config_action: String,
129+ /// The concurrency shown in the input: the admin's override, else what the runner reports.
130+ concurrency: String,
131+ /// "UI", "runner.toml" or empty when the runner has not reported.
132+ concurrency_source: &'static str,
133+ has_override: bool,
134+ running: u32,
135+}
136+
137+/// The effective concurrency as a number to show, and where it comes from.
138+fn concurrency_of(runner: &CiRunner) -> (String, &'static str) {
139+ if let Some(n) = runner.concurrency_override {
140+ return (n.to_string(), "UI");
141+ }
142+ let base = runner
143+ .reported
144+ .concurrency
145+ .or_else(|| {
146+ runner
147+ .reported_config
148+ .get("concurrency")
149+ .and_then(serde_json::Value::as_u64)
150+ .and_then(|n| u32::try_from(n).ok())
151+ })
152+ .map(|n| n.to_string());
153+ match base {
154+ Some(n) => (n, "runner.toml"),
155+ None => (String::new(), ""),
156+ }
67 }157 }
68 158
69 fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow {159 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 {
78 }168 }
79 None => (i18n::t(lang, Key::Never).to_owned(), String::new()),169 None => (i18n::t(lang, Key::Never).to_owned(), String::new()),
80 };170 };
171+ let (concurrency, concurrency_source) = concurrency_of(runner);
81 RunnerRow {172 RunnerRow {
82 name: runner.name.clone(),173 name: runner.name.clone(),
83 labels: runner.labels.clone(),174 labels: runner.labels.clone(),
@@ -86,6 +177,12 @@ fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow {
86 disabled: runner.disabled,177 disabled: runner.disabled,
87 toggle_action: format!("/admin/runners/{}/disabled", enc(&runner.id)),178 toggle_action: format!("/admin/runners/{}/disabled", enc(&runner.id)),
88 delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)),179 delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)),
180+ detail_href: format!("/admin/runners/{}", enc(&runner.id)),
181+ config_action: format!("/admin/runners/{}/config", enc(&runner.id)),
182+ concurrency,
183+ concurrency_source,
184+ has_override: runner.concurrency_override.is_some(),
185+ running: runner.running_jobs,
89 }186 }
90 }187 }
91 188
@@ -95,6 +192,9 @@ fn notice_from_query(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> {
95 let word = form_urlencoded::parse(query.as_bytes())192 let word = form_urlencoded::parse(query.as_bytes())
96 .find(|(key, _)| key == "notice")193 .find(|(key, _)| key == "notice")
97 .map(|(_, value)| value.into_owned())?;194 .map(|(_, value)| value.into_owned())?;
195+ if let Some((_, en, tr, is_error)) = EXTRA_NOTICES.iter().find(|(name, ..)| *name == word) {
196+ return Some((s(lang, en, tr), *is_error));
197+ }
98 NOTICES198 NOTICES
99 .iter()199 .iter()
100 .find(|(name, _, _)| *name == word)200 .find(|(name, _, _)| *name == word)
@@ -122,6 +222,7 @@ async fn runners_view(
122 note: String,222 note: String,
123 ) -> Result<impl View> {223 ) -> Result<impl View> {
124 Ok(view! {224 Ok(view! {
225+ <div data-live="/admin/runners/events">
125 <section class="page-head">226 <section class="page-head">
126 <h1>(g::t(lang, K::CiRunners))</h1>227 <h1>(g::t(lang, K::CiRunners))</h1>
127 </section>228 </section>
@@ -143,6 +244,8 @@ async fn runners_view(
143 <tr>244 <tr>
144 <th class="runner-name">(g::t(lang, K::TableName))</th>245 <th class="runner-name">(g::t(lang, K::TableName))</th>
145 <th class="runner-labels">(g::t(lang, K::TableLabels))</th>246 <th class="runner-labels">(g::t(lang, K::TableLabels))</th>
247+ <th class="runner-conc">(s(lang, "Concurrency", "Eşzamanlılık"))</th>
248+ <th class="runner-running">(s(lang, "Running", "Çalışan"))</th>
146 <th class="runner-seen">(g::t(lang, K::LastSeen))</th>249 <th class="runner-seen">(g::t(lang, K::LastSeen))</th>
147 <th class="runner-state">(g::t(lang, K::TableState))</th>250 <th class="runner-state">(g::t(lang, K::TableState))</th>
148 <th class="runner-actions"></th>251 <th class="runner-actions"></th>
@@ -151,7 +254,7 @@ async fn runners_view(
151 <tbody>254 <tbody>
152 for row in rows.iter() {255 for row in rows.iter() {
153 <tr>256 <tr>
154- <td class="runner-name"><strong>(row.name.as_str())</strong></td>257+ <td class="runner-name"><a href=(row.detail_href.as_str())><strong>(row.name.as_str())</strong></a></td>
155 <td class="runner-labels">258 <td class="runner-labels">
156 <span class="runner-label-list">259 <span class="runner-label-list">
157 for label in row.labels.iter() {260 for label in row.labels.iter() {
@@ -159,6 +262,10 @@ async fn runners_view(
159 }262 }
160 </span>263 </span>
161 </td>264 </td>
265+ <td class="runner-conc">
266+ 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")
267+ </td>
268+ <td class="runner-running small">(row.running.to_string())</td>
162 <td class="runner-seen small" title=(row.last_seen_full.as_str())>(row.last_seen.as_str())</td>269 <td class="runner-seen small" title=(row.last_seen_full.as_str())>(row.last_seen.as_str())</td>
163 <td class="runner-state">270 <td class="runner-state">
164 if row.disabled {271 if row.disabled {
@@ -195,6 +302,36 @@ async fn runners_view(
195 <button type="submit" class="primary">(g::t(lang, K::CreateRegistrationToken))</button>302 <button type="submit" class="primary">(g::t(lang, K::CreateRegistrationToken))</button>
196 </form>303 </form>
197 </section>304 </section>
305+ </div>
306+ })
307+}
308+
309+/// The inline number form for concurrency: input, Save, and a reset button while an override is set.
310+#[component]
311+async fn concurrency_form(
312+ lang: Lang,
313+ csrf: &str,
314+ action: &str,
315+ key: &str,
316+ value: &str,
317+ source: &'static str,
318+ has_override: bool,
319+ back: &'static str,
320+) -> Result<impl View> {
321+ Ok(view! {
322+ <form method="post" action=(action) class="inline-form runner-conc-form">
323+ <input type="hidden" name="csrf" value=(csrf)>
324+ <input type="hidden" name="key" value=(key)>
325+ <input type="hidden" name="back" value=(back)>
326+ <input type="number" name="value" value=(value) min="1" max="64" step="1" inputmode="numeric" required="required" aria-label=(s(lang, "Concurrency", "Eşzamanlılık"))>
327+ <button type="submit">(s(lang, "Save", "Kaydet"))</button>
328+ if has_override {
329+ <button type="submit" name="reset" value="1" formnovalidate="formnovalidate">(s(lang, "Use runner.toml value", "runner.toml değerini kullan"))</button>
330+ }
331+ if !source.is_empty() {
332+ <span class="muted small runner-source">(source)</span>
333+ }
334+ </form>
198 })335 })
199 }336 }
200 337
@@ -242,7 +379,7 @@ async fn runners_page(cx: &Cx) -> Result<impl View> {
242 let notice = notice_from_query(cx, lang);379 let notice = notice_from_query(cx, lang);
243 let note = g::token_ttl_note(380 let note = g::token_ttl_note(
244 lang,381 lang,
245- &g::hours_text(lang, state.config.ci.registration_token_hours),382+ &g::hours_text(lang, state.live().ci.registration_token_hours),
246 );383 );
247 let title = g::t(lang, K::CiRunners);384 let title = g::t(lang, K::CiRunners);
248 Ok(view! {385 Ok(view! {
@@ -260,7 +397,7 @@ async fn runner_token_create(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl
260 }397 }
261 let state = app_context::<AppState>(cx);398 let state = app_context::<AppState>(cx);
262 let lang = i18n::lang(cx, Some(&viewer.0));399 let lang = i18n::lang(cx, Some(&viewer.0));
263- let ttl_hours = state.config.ci.registration_token_hours;400+ let ttl_hours = state.live().ci.registration_token_hours;
264 let token = match state401 let token = match state
265 .store402 .store
266 .create_registration_token(&viewer.0.id, ttl_hours)403 .create_registration_token(&viewer.0.id, ttl_hours)
@@ -350,6 +487,312 @@ async fn runner_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther>
350 Ok(back_to_list("deleted"))487 Ok(back_to_list("deleted"))
351 }488 }
352 489
490+/// One row of the runner's config table, already formatted.
491+struct FieldRow {
492+ key: &'static str,
493+ /// The value in the input, or the text for a read-only field.
494+ value: String,
495+ source: &'static str,
496+ /// "live", "restart" or "read-only".
497+ kind: FieldKind,
498+ /// The override is stored but the runner has not started with it yet.
499+ pending: bool,
500+ has_override: bool,
501+ reported: bool,
502+}
503+
504+/// A JSON config value as the admin reads and types it: lists are comma separated.
505+fn show_value(value: &serde_json::Value) -> String {
506+ match value {
507+ serde_json::Value::String(text) => text.clone(),
508+ serde_json::Value::Array(items) => {
509+ items.iter().map(show_value).collect::<Vec<_>>().join(", ")
510+ }
511+ other => other.to_string(),
512+ }
513+}
514+
515+fn field_rows(runner: &CiRunner) -> Vec<FieldRow> {
516+ RUNNER_FIELDS
517+ .iter()
518+ .map(|field| {
519+ let reported = runner.reported_config.get(field.key);
520+ let overridden = if field.key == "concurrency" {
521+ runner.concurrency_override.map(serde_json::Value::from)
522+ } else {
523+ runner.config_overrides.get(field.key).cloned()
524+ };
525+ let live_concurrency = (field.key == "concurrency")
526+ .then(|| runner.reported.concurrency.map(serde_json::Value::from))
527+ .flatten();
528+ let shown = live_concurrency
529+ .clone()
530+ .or_else(|| overridden.clone())
531+ .or_else(|| reported.cloned());
532+ // Restart fields wait for a start; a live concurrency waits for the next check-in.
533+ let pending = match (&overridden, field.kind) {
534+ (Some(want), FieldKind::Restart) => reported != Some(want),
535+ (Some(want), FieldKind::Live) if field.key == "concurrency" => {
536+ live_concurrency.as_ref() != Some(want)
537+ }
538+ _ => false,
539+ };
540+ FieldRow {
541+ key: field.key,
542+ value: shown.as_ref().map(show_value).unwrap_or_default(),
543+ source: if overridden.is_some() {
544+ "UI"
545+ } else {
546+ "runner.toml"
547+ },
548+ kind: field.kind,
549+ pending,
550+ has_override: overridden.is_some(),
551+ reported: shown.is_some(),
552+ }
553+ })
554+ .collect()
555+}
556+
557+/// The input for one editable field.
558+#[component]
559+async fn field_input(key: &'static str, value: &str, lang: Lang) -> Result<impl View> {
560+ let aria = key;
561+ Ok(view! {
562+ if key == "auto_update" {
563+ <select name="value" aria-label=(aria)>
564+ <option value="true" selected=(sel(value == "true"))>"true"</option>
565+ <option value="false" selected=(sel(value == "false"))>"false"</option>
566+ </select>
567+ } else if key == "executor" {
568+ <select name="value" aria-label=(aria)>
569+ <option value="builtin" selected=(sel(value == "builtin"))>"builtin"</option>
570+ <option value="podman" selected=(sel(value == "podman"))>"podman"</option>
571+ </select>
572+ } else if key == "sandbox.userns" {
573+ <select name="value" aria-label=(aria)>
574+ <option value="auto" selected=(sel(value == "auto"))>"auto"</option>
575+ <option value="single" selected=(sel(value == "single"))>"single"</option>
576+ <option value="subuid" selected=(sel(value == "subuid"))>"subuid"</option>
577+ </select>
578+ } else if matches!(key, "limits.pids" | "limits.image_max_gb" | "images.keep_days" | "cache_max_gib" | "concurrency") {
579+ <input type="number" name="value" value=(value) step="1" inputmode="numeric" aria-label=(aria) min=(if key == "concurrency" { "1" } else { "0" }) max=(if key == "concurrency" { Some("64") } else { None })>
580+ } else {
581+ <input type="text" name="value" value=(value) aria-label=(aria) placeholder=(s(lang, "(from runner.toml)", "(runner.toml'dan)")) autocomplete="off" spellcheck="false">
582+ }
583+ })
584+}
585+
586+fn sel(on: bool) -> Option<&'static str> {
587+ on.then_some("selected")
588+}
589+
590+fn bytes_text(bytes: u64) -> String {
591+ let gib = bytes as f64 / (1u64 << 30) as f64;
592+ format!("{gib:.1} GiB")
593+}
594+
595+#[component]
596+async fn runner_detail_view(
597+ lang: Lang,
598+ csrf: String,
599+ runner: CiRunner,
600+ row: RunnerRow,
601+ fields: Vec<FieldRow>,
602+ notice: Option<(&'static str, bool)>,
603+ action: String,
604+) -> Result<impl View> {
605+ let host_version = runner.reported.version.clone().unwrap_or_default();
606+ let host_cpus = runner
607+ .reported
608+ .cpus
609+ .map(|n| n.to_string())
610+ .unwrap_or_default();
611+ let host_mem = runner
612+ .reported
613+ .memory_bytes
614+ .map(bytes_text)
615+ .unwrap_or_default();
616+ Ok(view! {
617+ <div data-live="/admin/runners/events">
618+ <section class="page-head">
619+ <h1>(runner.name.as_str())</h1>
620+ <p><a href="/admin/runners">(g::t(lang, K::BackToRunners))</a></p>
621+ </section>
622+ if let Some((text, is_error)) = notice {
623+ if is_error {
624+ <section class="card notice alert" role="alert">(text)</section>
625+ } else {
626+ <section class="card notice" role="status">(text)</section>
627+ }
628+ }
629+ <section class="card">
630+ <h2>(s(lang, "Status", "Durum"))</h2>
631+ <dl class="runner-facts">
632+ <dt>(s(lang, "Running jobs", "Çalışan işler"))</dt><dd>(row.running.to_string())</dd>
633+ <dt>(g::t(lang, K::LastSeen))</dt><dd title=(row.last_seen_full.as_str())>(row.last_seen.as_str())</dd>
634+ if !host_version.is_empty() {
635+ <dt>(s(lang, "Runner version", "Çalıştırıcı sürümü"))</dt><dd>(host_version.as_str())</dd>
636+ }
637+ if !host_cpus.is_empty() {
638+ <dt>(s(lang, "CPUs", "CPU sayısı"))</dt><dd>(host_cpus.as_str())</dd>
639+ }
640+ if !host_mem.is_empty() {
641+ <dt>(s(lang, "Memory", "Bellek"))</dt><dd>(host_mem.as_str())</dd>
642+ }
643+ </dl>
644+ </section>
645+ <section class="card">
646+ <h2>(s(lang, "Configuration", "Yapılandırma"))</h2>
647+ <p class="muted small">(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."))</p>
648+ <div class="table-wrap">
649+ <table class="table runner-config">
650+ <thead>
651+ <tr>
652+ <th>(s(lang, "Field", "Alan"))</th>
653+ <th>(s(lang, "Value", "Değer"))</th>
654+ <th>(s(lang, "Source", "Kaynak"))</th>
655+ <th>(s(lang, "Applies", "Uygulanma"))</th>
656+ </tr>
657+ </thead>
658+ <tbody>
659+ for f in fields.iter() {
660+ <tr>
661+ <td><code>(f.key)</code></td>
662+ if f.kind == FieldKind::ReadOnly {
663+ <td colspan="1">
664+ if f.reported { <span class="runner-value">(f.value.as_str())</span> } else { <span class="muted">"-"</span> }
665+ </td>
666+ <td class="small muted">(if f.reported { "runner.toml" } else { "" })</td>
667+ <td><span class="runner-label">(s(lang, "read-only", "salt okunur"))</span></td>
668+ } else {
669+ <td>
670+ <form method="post" action=(action.as_str()) class="inline-form runner-conc-form">
671+ <input type="hidden" name="csrf" value=(csrf.as_str())>
672+ <input type="hidden" name="key" value=(f.key)>
673+ <input type="hidden" name="back" value="detail">
674+ field_input(key: f.key, value: f.value.as_str(), lang: lang)
675+ <button type="submit">(s(lang, "Save", "Kaydet"))</button>
676+ if f.has_override {
677+ <button type="submit" name="reset" value="1" formnovalidate="formnovalidate">(s(lang, "Use runner.toml value", "runner.toml değerini kullan"))</button>
678+ }
679+ </form>
680+ </td>
681+ <td class="small muted">(if f.reported || f.has_override { f.source } else { "" })</td>
682+ <td>
683+ if f.kind == FieldKind::Live {
684+ <span class="ci-state ci-success">(if f.pending { s(lang, "live, pending", "canlı, bekliyor") } else { s(lang, "live", "canlı") })</span>
685+ } else {
686+ <span class="ci-state runner-disabled">(if f.pending { s(lang, "restart needed", "yeniden başlatma gerekli") } else { s(lang, "applies on restart", "yeniden başlatınca") })</span>
687+ }
688+ </td>
689+ }
690+ </tr>
691+ }
692+ </tbody>
693+ </table>
694+ </div>
695+ </section>
696+ </div>
697+ })
698+}
699+
700+/// One runner with its status and every config field. Instance admins only.
701+#[page("/admin/runners/{runner_id}")]
702+async fn runner_detail_page(cx: &Cx) -> Result<impl View> {
703+ let viewer = admin_only(cx).await?;
704+ let lang = i18n::lang(cx, Some(&viewer.0));
705+ let state = app_context::<AppState>(cx);
706+ let id = path_param::<RunnerId>(cx);
707+ let Some(runner) = runner_named(state, id).await? else {
708+ return Err(back_to_list("missing").into());
709+ };
710+ let row = runner_row(&runner, &viewer.0.timezone, lang, now_unix());
711+ let fields = field_rows(&runner);
712+ let csrf = viewer.1.csrf_token.clone();
713+ let notice = notice_from_query(cx, lang);
714+ let action = row.config_action.clone();
715+ let title = runner.name.clone();
716+ Ok(view! {
717+ 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))
718+ })
719+}
720+
721+/// The live `changed` stream of the runners pages. Sent on a runner's report, claim, finish or an
722+/// admin edit; nothing is sent on connect.
723+#[route(GET "/admin/runners/events")]
724+async fn runners_events(cx: &Cx) -> Result<Response> {
725+ admin_only(cx).await?;
726+ let state = app_context::<AppState>(cx);
727+ let wake = state.ci_live.subscribe_runners();
728+ let events = futures_util::stream::unfold(wake, |mut wake| async move {
729+ wake.changed().await.ok()?;
730+ Some((
731+ crate::pages::ci_runs::changed_event("runners".to_owned()),
732+ wake,
733+ ))
734+ });
735+ events_response(cx, events)
736+}
737+
738+/// Sets or resets one config field of a runner. Concurrency and labels are live; the rest are
739+/// stored for the runner's next start. Read-only fields and bad values change nothing.
740+#[route(POST "/admin/runners/{runner_id}/config")]
741+async fn runner_set_config(cx: &Cx, Form(form): Form<ConfigForm>) -> Result<SeeOther> {
742+ let viewer = admin_only(cx).await?;
743+ if !check_csrf(&viewer.1, &form.csrf) {
744+ return Err(forbidden().into());
745+ }
746+ let id = path_param::<RunnerId>(cx);
747+ let state = app_context::<AppState>(cx);
748+ let back = |notice: &str| {
749+ if form.back == "detail" {
750+ see_other(format!("/admin/runners/{}?notice={}", enc(id), enc(notice)))
751+ } else {
752+ back_to_list(notice)
753+ }
754+ };
755+ if runner_named(state, id).await?.is_none() {
756+ return Ok(back_to_list("missing"));
757+ }
758+ let Some(field) = runner_field(&form.key) else {
759+ return Ok(back("read-only"));
760+ };
761+ if field.kind == FieldKind::ReadOnly {
762+ return Ok(back("read-only"));
763+ }
764+ let reset = form.reset == "1";
765+ let value = (!reset).then_some(form.value.as_str());
766+ match state.store.set_runner_field(id, field.key, value).await {
767+ Ok(()) => {}
768+ Err(forge_core::Error::Invalid(_)) => return Ok(back("invalid")),
769+ Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")),
770+ Err(e) => return Err(e.into()),
771+ }
772+ state.ci_live.bump_runners();
773+ tracing::info!(actor_id = %viewer.0.id, runner_id = %id, field = field.key, reset, "ci runner config changed");
774+ audit::record(
775+ &state.store,
776+ Some(cx),
777+ Actor::User(&viewer.0),
778+ AuditAction::CiRunnerConfigChanged,
779+ Target {
780+ kind: "ci_runner",
781+ id,
782+ name: "",
783+ },
784+ serde_json::json!({ "field": field.key, "reset": reset }),
785+ )
786+ .await;
787+ Ok(back(if reset {
788+ "reset"
789+ } else if field.kind == FieldKind::Live {
790+ "saved"
791+ } else {
792+ "saved-restart"
793+ }))
794+}
795+
353 #[cfg(test)]796 #[cfg(test)]
354 mod tests {797 mod tests {
355 use super::*;798 use super::*;
@@ -620,4 +1063,154 @@ mod tests {
620 .await;1063 .await;
621 assert!(page.contains("No runner has that id"));1064 assert!(page.contains("No runner has that id"));
622 }1065 }
1066+
1067+ async fn one_runner(store: &Store, router: &Router) -> forge_core::ci::CiRunner {
1068+ let (_, created) = send(
1069+ router,
1070+ "POST",
1071+ "/admin/runners/tokens",
1072+ Some(ADMIN_TOKEN),
1073+ csrf_form(""),
1074+ )
1075+ .await;
1076+ let token = created
1077+ .split("--token ")
1078+ .nth(1)
1079+ .and_then(|rest| rest.split(' ').next())
1080+ .expect("token")
1081+ .to_owned();
1082+ store
1083+ .register_runner(&token, "tahinli-box", &["linux".to_owned()])
1084+ .await
1085+ .expect("register");
1086+ store.list_runners().await.expect("list").remove(0)
1087+ }
1088+
1089+ #[tokio::test]
1090+ async fn admin_sets_and_resets_concurrency_and_config_fields() {
1091+ let dir = tempfile::tempdir().expect("tempdir");
1092+ let (store, router) = fixture(dir.path()).await;
1093+ let runner = one_runner(&store, &router).await;
1094+ let action = format!("/admin/runners/{}/config", runner.id);
1095+
1096+ let (status, _) = send(
1097+ &router,
1098+ "POST",
1099+ &action,
1100+ Some(ADMIN_TOKEN),
1101+ csrf_form("&key=concurrency&value=3&back=list"),
1102+ )
1103+ .await;
1104+ assert_eq!(status, 303);
1105+ assert_eq!(
1106+ store.list_runners().await.unwrap()[0].concurrency_override,
1107+ Some(3)
1108+ );
1109+ let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
1110+ assert!(list.contains(r#"value="3""#));
1111+ assert!(list.contains("Use runner.toml value"));
1112+ assert!(list.contains(r#"data-live="/admin/runners/events""#));
1113+
1114+ // Out of range, wrong kind of field and a read-only field change nothing.
1115+ for form in [
1116+ "&key=concurrency&value=65",
1117+ "&key=concurrency&value=0",
1118+ "&key=concurrency&value=abc",
1119+ "&key=url&value=https://x.example",
1120+ "&key=runner_secret&value=x",
1121+ ] {
1122+ let (status, _) =
1123+ send(&router, "POST", &action, Some(ADMIN_TOKEN), csrf_form(form)).await;
1124+ assert_eq!(status, 303, "{form}");
1125+ }
1126+ assert_eq!(
1127+ store.list_runners().await.unwrap()[0].concurrency_override,
1128+ Some(3)
1129+ );
1130+
1131+ let (status, _) = send(
1132+ &router,
1133+ "POST",
1134+ &action,
1135+ Some(ADMIN_TOKEN),
1136+ csrf_form("&key=limits.memory&value=8g&back=detail"),
1137+ )
1138+ .await;
1139+ assert_eq!(status, 303);
1140+ let detail_uri = format!("/admin/runners/{}", runner.id);
1141+ let (status, detail) = send(&router, "GET", &detail_uri, Some(ADMIN_TOKEN), None).await;
1142+ assert_eq!(status, 200);
1143+ assert!(detail.contains("limits.memory"));
1144+ assert!(detail.contains("restart needed"));
1145+ assert!(detail.contains("read-only"));
1146+ assert!(detail.contains(r#"data-live="/admin/runners/events""#));
1147+
1148+ let (_, _) = send(
1149+ &router,
1150+ "POST",
1151+ &action,
1152+ Some(ADMIN_TOKEN),
1153+ csrf_form("&key=concurrency&reset=1"),
1154+ )
1155+ .await;
1156+ let (_, _) = send(
1157+ &router,
1158+ "POST",
1159+ &action,
1160+ Some(ADMIN_TOKEN),
1161+ csrf_form("&key=limits.memory&reset=1"),
1162+ )
1163+ .await;
1164+ let after = store.list_runners().await.unwrap().remove(0);
1165+ assert_eq!(after.concurrency_override, None);
1166+ assert!(after.config_overrides.is_empty());
1167+ }
1168+
1169+ #[tokio::test]
1170+ async fn config_posts_need_admin_and_csrf_and_the_events_stream_is_admin_only() {
1171+ let dir = tempfile::tempdir().expect("tempdir");
1172+ let (store, router) = fixture(dir.path()).await;
1173+ let runner = one_runner(&store, &router).await;
1174+ let action = format!("/admin/runners/{}/config", runner.id);
1175+ let (status, _) = send(
1176+ &router,
1177+ "POST",
1178+ &action,
1179+ Some(USER_TOKEN),
1180+ csrf_form("&key=concurrency&value=2"),
1181+ )
1182+ .await;
1183+ assert_eq!(status, 404);
1184+ let (status, _) = send(
1185+ &router,
1186+ "POST",
1187+ &action,
1188+ Some(ADMIN_TOKEN),
1189+ Some("csrf=wrong&key=concurrency&value=2".into()),
1190+ )
1191+ .await;
1192+ assert_eq!(status, 403);
1193+ assert_eq!(
1194+ store.list_runners().await.unwrap()[0].concurrency_override,
1195+ None
1196+ );
1197+ let (status, _) = send(
1198+ &router,
1199+ "GET",
1200+ "/admin/runners/events",
1201+ Some(USER_TOKEN),
1202+ None,
1203+ )
1204+ .await;
1205+ assert_eq!(status, 404);
1206+ let (status, _) = send(
1207+ &router,
1208+ "GET",
1209+ &format!("/admin/runners/{}", runner.id),
1210+ Some(USER_TOKEN),
1211+ None,
1212+ )
1213+ .await;
1214+ assert_eq!(status, 404);
1215+ }
623 }1216 }
crates/forge-web/src/pages/admin_server.rsadded+690 -0
@@ -0,0 +1,690 @@
1+//! Page: the forge's own settings (`/admin/server`). Instance admins only; anyone else gets 404.
2+//!
3+//! One tab per group of settings. Each field shows its effective value, where that value comes
4+//! from (default, config file, or a UI override) and how a change reaches the process: live
5+//! (applied at once), restart (saved, applied at the next start) or read-only. Saving a tab stores
6+//! the changed fields as database overrides on top of the config file, which is never rewritten.
7+//! A field with an override has "Reset to file value". Secret fields are write-only: the page
8+//! shows only whether they are set. See `forge_core::server_settings` for the rules.
9+//! Saving and resetting are audited, with the keys but never the values.
10+
11+use std::collections::{BTreeMap, HashMap};
12+
13+use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty};
14+use forge_core::{AuditAction, Error};
15+use serde::Deserialize;
16+use topcoat::Result;
17+use topcoat::context::{Cx, app_context};
18+use topcoat::router::content::Form;
19+use topcoat::router::error::{forbidden, see_other};
20+use topcoat::router::response::Response;
21+use topcoat::router::{page, query_params, route};
22+use topcoat::view::{View, component, view};
23+
24+use crate::audit::{self, Actor, Target};
25+use crate::auth::check_csrf;
26+use crate::i18n::admin::{self as g, K};
27+use crate::i18n::{self, Key, Lang};
28+use crate::pages::admin_users::admin_only;
29+use crate::state::AppState;
30+use crate::views::{enc, shell};
31+
32+#[query_params(error = bad_request)]
33+pub(crate) struct ServerQuery {
34+ notice: Option<String>,
35+ tab: Option<String>,
36+}
37+
38+struct OptionRow {
39+ value: String,
40+ label: String,
41+ selected: bool,
42+}
43+
44+/// One field, already formatted for the template. A secret's value is never in here.
45+struct Row {
46+ key: &'static str,
47+ label: &'static str,
48+ help: &'static str,
49+ kind_label: &'static str,
50+ kind_class: &'static str,
51+ source_label: &'static str,
52+ value: String,
53+ file_value: String,
54+ show_file_value: bool,
55+ has_override: bool,
56+ pending: bool,
57+ checked: bool,
58+ min: String,
59+ max: String,
60+ options: Vec<OptionRow>,
61+ secret_state: &'static str,
62+ is_bool: bool,
63+ is_number: bool,
64+ is_select: bool,
65+ is_secret: bool,
66+ fixed: bool,
67+}
68+
69+fn tab_label(lang: Lang, group: Group) -> &'static str {
70+ g::t(
71+ lang,
72+ match group {
73+ Group::General => K::SrvTabGeneral,
74+ Group::Limits => K::SrvTabLimits,
75+ Group::Storage => K::SrvTabStorage,
76+ Group::Backups => K::SrvTabBackups,
77+ Group::Integrations => K::SrvTabIntegrations,
78+ },
79+ )
80+}
81+
82+fn tab_class(on: bool) -> &'static str {
83+ if on {
84+ "subnav-link current"
85+ } else {
86+ "subnav-link"
87+ }
88+}
89+
90+fn row(lang: Lang, view: &FieldView) -> Row {
91+ let field: &Field = view.field;
92+ let (kind_label, kind_class) = match field.kind {
93+ Kind::Live => (g::t(lang, K::SrvKindLive), "badge srv-live"),
94+ Kind::Restart => (g::t(lang, K::SrvKindRestart), "badge srv-restart"),
95+ Kind::ReadOnly => (g::t(lang, K::SrvKindReadOnly), "badge srv-ro"),
96+ };
97+ let source_label = match view.source {
98+ Source::Default => g::t(lang, K::SrvSourceDefault),
99+ Source::File => g::t(lang, K::SrvSourceFile),
100+ Source::Ui => g::t(lang, K::SrvSourceUi),
101+ };
102+ let (min, max) = match field.ty {
103+ Ty::Uint(min, max) => (min.to_string(), max.to_string()),
104+ _ => (String::new(), String::new()),
105+ };
106+ let options = match field.ty {
107+ Ty::Choice(all) => all
108+ .iter()
109+ .map(|option| OptionRow {
110+ value: (*option).to_owned(),
111+ label: if option.is_empty() {
112+ g::t(lang, K::SrvEmpty).to_owned()
113+ } else {
114+ (*option).to_owned()
115+ },
116+ selected: *option == view.value,
117+ })
118+ .collect(),
119+ _ => Vec::new(),
120+ };
121+ let editable = field.kind != Kind::ReadOnly;
122+ Row {
123+ key: field.key,
124+ label: field.label,
125+ help: field.help,
126+ kind_label,
127+ kind_class,
128+ source_label,
129+ value: view.value.clone(),
130+ file_value: if view.file_value.is_empty() {
131+ g::t(lang, K::SrvEmpty).to_owned()
132+ } else {
133+ view.file_value.clone()
134+ },
135+ show_file_value: editable && view.source == Source::Ui && !field.is_secret(),
136+ has_override: editable && view.source == Source::Ui,
137+ pending: view.restart_pending,
138+ checked: view.value == "true",
139+ min,
140+ max,
141+ options,
142+ secret_state: if view.secret_set {
143+ g::t(lang, K::SrvSecretSet)
144+ } else {
145+ g::t(lang, K::SrvSecretNotSet)
146+ },
147+ is_bool: field.ty == Ty::Bool && editable,
148+ is_number: matches!(field.ty, Ty::Uint(..)) && editable,
149+ is_select: matches!(field.ty, Ty::Choice(_)) && editable,
150+ is_secret: field.is_secret(),
151+ fixed: !editable,
152+ }
153+}
154+
155+async fn rows_for(state: &AppState, lang: Lang, group: Group) -> forge_core::Result<Vec<Row>> {
156+ let overrides = state.store.server_overrides().await?;
157+ Ok(state
158+ .settings
159+ .views(&overrides)
160+ .iter()
161+ .filter(|view| view.field.group == group)
162+ .map(|view| row(lang, view))
163+ .collect())
164+}
165+
166+#[component]
167+async fn server_view(
168+ lang: Lang,
169+ csrf: String,
170+ group: Group,
171+ rows: Vec<Row>,
172+ notice: Option<String>,
173+) -> Result<impl View> {
174+ let tab = group.slug();
175+ let any_editable = rows.iter().any(|r| !r.fixed);
176+ Ok(view! {
177+ <section class="page-head">
178+ <h1>(g::t(lang, K::ServerSettings))</h1>
179+ <p class="muted">(g::t(lang, K::ServerSettingsIntro))</p>
180+ </section>
181+ <nav class="subnav" aria-label=(g::t(lang, K::ServerSettings))>
182+ for g_tab in Group::ALL.into_iter() {
183+ <a class=(tab_class(g_tab == group)) href=(format!("/admin/server?tab={}", g_tab.slug()))>(tab_label(lang, g_tab))</a>
184+ }
185+ </nav>
186+ if let Some(message) = notice {
187+ <section class="card notice" role="status">
188+ <p>(message.as_str())</p>
189+ </section>
190+ }
191+ <section class="card">
192+ <form method="post" action="/admin/server" class="srv-form">
193+ <input type="hidden" name="csrf" value=(csrf.as_str())>
194+ <input type="hidden" name="tab" value=(tab)>
195+ <div class="srv-grid">
196+ for r in rows.iter() {
197+ <div class="srv-field">
198+ <div class="srv-head">
199+ <span class="srv-label">(r.label)</span>
200+ <span class=(r.kind_class)>(r.kind_label)</span>
201+ <span class="badge srv-source">(r.source_label)</span>
202+ if r.pending {
203+ <span class="badge srv-pending">(g::t(lang, K::SrvRestartNeeded))</span>
204+ }
205+ </div>
206+ if r.is_bool {
207+ <label class="inline"><input type="checkbox" name=(r.key) value="true" checked=(r.checked)><span>(r.label)</span></label>
208+ } else if r.is_select {
209+ <select name=(r.key) aria-label=(r.label)>
210+ for option in r.options.iter() {
211+ <option value=(option.value.as_str()) selected=(option.selected)>(option.label.as_str())</option>
212+ }
213+ </select>
214+ } else if r.is_number {
215+ <input type="number" name=(r.key) value=(r.value.as_str()) min=(r.min.as_str()) max=(r.max.as_str()) aria-label=(r.label)>
216+ } else if r.is_secret {
217+ <input type="password" name=(r.key) autocomplete="new-password" maxlength="1024" aria-label=(r.label)>
218+ <p class="muted small"><strong>(r.secret_state)</strong> ". " (g::t(lang, K::SrvSecretHint))</p>
219+ } else if r.fixed {
220+ <code class="srv-fixed">(r.value.as_str())</code>
221+ } else {
222+ <input type="text" name=(r.key) value=(r.value.as_str()) maxlength="1024" autocomplete="off" aria-label=(r.label)>
223+ }
224+ if !r.help.is_empty() {
225+ <p class="muted small">(r.help)</p>
226+ }
227+ if r.has_override {
228+ <p class="small srv-reset">
229+ if r.show_file_value {
230+ <span class="muted">(g::t(lang, K::SrvFileValue)) ": " <code>(r.file_value.as_str())</code></span>
231+ }
232+ <button type="submit" form="srv-reset" name="key" value=(r.key)>(g::t(lang, K::SrvResetToFile))</button>
233+ </p>
234+ }
235+ </div>
236+ }
237+ </div>
238+ if any_editable {
239+ <div class="actions">
240+ <button type="submit" class="primary">(i18n::t(lang, Key::Save))</button>
241+ </div>
242+ }
243+ </form>
244+ <form id="srv-reset" method="post" action="/admin/server/reset">
245+ <input type="hidden" name="csrf" value=(csrf.as_str())>
246+ <input type="hidden" name="tab" value=(tab)>
247+ </form>
248+ </section>
249+ })
250+}
251+
252+#[page("/admin/server")]
253+async fn server_page(cx: &Cx) -> Result<impl View> {
254+ let viewer = admin_only(cx).await?;
255+ let query = query_params::<ServerQuery>(cx)?;
256+ let state = app_context::<AppState>(cx);
257+ let lang = i18n::lang(cx, Some(&viewer.0));
258+ let group = query
259+ .tab
260+ .as_deref()
261+ .and_then(Group::parse)
262+ .unwrap_or(Group::General);
263+ let rows = rows_for(state, lang, group).await?;
264+ let csrf = viewer.1.csrf_token.clone();
265+ let title = g::t(lang, K::ServerSettings);
266+ Ok(view! {
267+ shell(title: title, viewer: Some(&viewer), server_view(lang: lang, csrf: csrf, group: group, rows: rows, notice: query.notice.clone()))
268+ })
269+}
270+
271+#[route(POST "/admin/server")]
272+async fn server_save(cx: &Cx, Form(mut form): Form<HashMap<String, String>>) -> Result<Response> {
273+ let viewer = admin_only(cx).await?;
274+ if !check_csrf(&viewer.1, form.get("csrf").map_or("", String::as_str)) {
275+ return Err(forbidden().into());
276+ }
277+ let lang = i18n::lang(cx, Some(&viewer.0));
278+ let state = app_context::<AppState>(cx);
279+ let group = form
280+ .get("tab")
281+ .and_then(|t| Group::parse(t))
282+ .unwrap_or(Group::General);
283+ // An unchecked box is absent from the post.
284+ for field in ss::FIELDS
285+ .iter()
286+ .filter(|f| f.group == group && f.ty == Ty::Bool && f.kind != Kind::ReadOnly)
287+ {
288+ form.entry(field.key.to_owned())
289+ .or_insert_with(|| "false".to_owned());
290+ }
291+ let submitted: BTreeMap<String, String> = form.into_iter().collect();
292+ let notice = match save(cx, state, &viewer.0, group, &submitted, lang).await {
293+ Ok(Some(())) => g::t(lang, K::SrvSaved).to_owned(),
294+ Ok(None) => g::t(lang, K::SrvNothingChanged).to_owned(),
295+ Err(Error::Invalid(message)) => message,
296+ Err(Error::Config(message)) => message,
297+ Err(other) => other.to_string(),
298+ };
299+ Err(see_other(format!(
300+ "/admin/server?tab={}&notice={}",
301+ group.slug(),
302+ enc(&notice)
303+ ))
304+ .into())
305+}
306+
307+/// Validates the whole tab as one unit, stores it, publishes the live fields and audits the keys.
308+/// `Ok(None)` means nothing differed from what is already in effect.
309+async fn save(
310+ cx: &Cx,
311+ state: &AppState,
312+ user: &forge_core::User,
313+ group: Group,
314+ submitted: &BTreeMap<String, String>,
315+ _lang: Lang,
316+) -> forge_core::Result<Option<()>> {
317+ let existing = state.store.server_overrides().await?;
318+ let plan = state.settings.plan_save(&existing, group, submitted)?;
319+ if plan.sets.is_empty() && plan.clears.is_empty() {
320+ return Ok(None);
321+ }
322+ state.store.set_server_overrides(&plan.sets).await?;
323+ for key in &plan.clears {
324+ state.store.clear_server_override(key).await?;
325+ }
326+ state.settings.publish(&plan.overrides)?;
327+ let keys: Vec<&str> = plan.sets.iter().map(|(k, _)| k.as_str()).collect();
328+ audit::record(
329+ &state.store,
330+ Some(cx),
331+ Actor::User(user),
332+ AuditAction::ServerSettingsUpdated,
333+ Target {
334+ kind: "server",
335+ id: "",
336+ name: "",
337+ },
338+ serde_json::json!({ "set": keys, "cleared": plan.clears }),
339+ )
340+ .await;
341+ Ok(Some(()))
342+}
343+
344+#[derive(Deserialize, Default)]
345+struct ResetForm {
346+ #[serde(default)]
347+ csrf: String,
348+ #[serde(default)]
349+ tab: String,
350+ #[serde(default)]
351+ key: String,
352+}
353+
354+#[route(POST "/admin/server/reset")]
355+async fn server_reset(cx: &Cx, Form(form): Form<ResetForm>) -> Result<Response> {
356+ let viewer = admin_only(cx).await?;
357+ if !check_csrf(&viewer.1, &form.csrf) {
358+ return Err(forbidden().into());
359+ }
360+ let lang = i18n::lang(cx, Some(&viewer.0));
361+ let state = app_context::<AppState>(cx);
362+ let group = Group::parse(&form.tab).unwrap_or(Group::General);
363+ let notice = match reset(cx, state, &viewer.0, &form.key).await {
364+ Ok(()) => g::t(lang, K::SrvResetDone).to_owned(),
365+ Err(Error::Invalid(message)) => message,
366+ Err(Error::Config(message)) => message,
367+ Err(other) => other.to_string(),
368+ };
369+ Err(see_other(format!(
370+ "/admin/server?tab={}&notice={}",
371+ group.slug(),
372+ enc(&notice)
373+ ))
374+ .into())
375+}
376+
377+async fn reset(
378+ cx: &Cx,
379+ state: &AppState,
380+ user: &forge_core::User,
381+ key: &str,
382+) -> forge_core::Result<()> {
383+ let existing = state.store.server_overrides().await?;
384+ let next = state.settings.plan_reset(&existing, key)?;
385+ state.store.clear_server_override(key).await?;
386+ state.settings.publish(&next)?;
387+ audit::record(
388+ &state.store,
389+ Some(cx),
390+ Actor::User(user),
391+ AuditAction::ServerSettingsUpdated,
392+ Target {
393+ kind: "server",
394+ id: "",
395+ name: "",
396+ },
397+ serde_json::json!({ "set": [], "cleared": [key] }),
398+ )
399+ .await;
400+ Ok(())
401+}
402+
403+#[cfg(test)]
404+mod tests {
405+ use super::*;
406+ use topcoat::router::request::Request;
407+ use topcoat::router::{Body, Router, to_bytes};
408+
409+ use crate::auth::SESSION_COOKIE;
410+ use crate::test_support::{app_router, create_session, test_state};
411+
412+ const ADMIN_TOKEN: &str = "server-admin-session";
413+ const USER_TOKEN: &str = "server-user-session";
414+ const CSRF: &str = "server-csrf";
415+
416+ struct Fixture {
417+ _dir: tempfile::TempDir,
418+ router: Router,
419+ state: AppState,
420+ }
421+
422+ async fn fixture() -> Fixture {
423+ let dir = tempfile::tempdir().expect("tempdir");
424+ let data_dir = dir.path().join("data");
425+ std::fs::create_dir_all(&data_dir).expect("data dir");
426+ let state = test_state(&data_dir).await;
427+ let admin = state
428+ .store
429+ .create_user("tahinli", Some("admin@example.com"), "h", true)
430+ .await
431+ .expect("admin");
432+ let user = state
433+ .store
434+ .create_user("plain", None, "h", false)
435+ .await
436+ .expect("user");
437+ create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await;
438+ create_session(&state.store, &user.id, USER_TOKEN, CSRF).await;
439+ let router = app_router(state.clone());
440+ Fixture {
441+ _dir: dir,
442+ router,
443+ state,
444+ }
445+ }
446+
447+ async fn send(
448+ router: &Router,
449+ method: &str,
450+ uri: &str,
451+ token: Option<&str>,
452+ form: Option<String>,
453+ ) -> (u16, String, String) {
454+ let mut builder = Request::builder().method(method).uri(uri);
455+ if let Some(token) = token {
456+ builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
457+ }
458+ let body = match form {
459+ Some(form) => {
460+ builder = builder.header("content-type", "application/x-www-form-urlencoded");
461+ Body::from(form)
462+ }
463+ None => Body::empty(),
464+ };
465+ let res = router.handle(builder.body(body).expect("request")).await;
466+ let status = res.status().as_u16();
467+ let location = res
468+ .headers()
469+ .get("location")
470+ .and_then(|v| v.to_str().ok())
471+ .unwrap_or_default()
472+ .to_owned();
473+ let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
474+ (
475+ status,
476+ String::from_utf8_lossy(&bytes).into_owned(),
477+ location,
478+ )
479+ }
480+
481+ async fn admin_get(fx: &Fixture, uri: &str) -> String {
482+ let (status, body, _) = send(&fx.router, "GET", uri, Some(ADMIN_TOKEN), None).await;
483+ assert_eq!(status, 200, "GET {uri}");
484+ body
485+ }
486+
487+ /// Posts a tab and follows the redirect to read the notice it shows.
488+ async fn save(fx: &Fixture, tab: &str, fields: &str) -> String {
489+ let form = format!("csrf={CSRF}&tab={tab}&{fields}");
490+ let (status, _, location) = send(
491+ &fx.router,
492+ "POST",
493+ "/admin/server",
494+ Some(ADMIN_TOKEN),
495+ Some(form),
496+ )
497+ .await;
498+ assert_eq!(status, 303);
499+ admin_get(fx, &location).await
500+ }
501+
502+ #[tokio::test]
503+ async fn the_page_and_its_posts_are_404_for_anonymous_and_non_admins() {
504+ let fx = fixture().await;
505+ for token in [None, Some(USER_TOKEN)] {
506+ let (get, _, _) = send(&fx.router, "GET", "/admin/server", token, None).await;
507+ assert_eq!(get, 404);
508+ let form = format!("csrf={CSRF}&tab=limits&ci.max_log_mb=99");
509+ let (post, _, _) = send(&fx.router, "POST", "/admin/server", token, Some(form)).await;
510+ assert_eq!(post, 404);
511+ let form = format!("csrf={CSRF}&tab=limits&key=ci.max_log_mb");
512+ let (post, _, _) =
513+ send(&fx.router, "POST", "/admin/server/reset", token, Some(form)).await;
514+ assert_eq!(post, 404);
515+ }
516+ assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
517+ }
518+
519+ #[tokio::test]
520+ async fn a_bad_csrf_token_is_refused() {
521+ let fx = fixture().await;
522+ let form = "csrf=wrong&tab=limits&ci.max_log_mb=99".to_owned();
523+ let (status, _, _) = send(
524+ &fx.router,
525+ "POST",
526+ "/admin/server",
527+ Some(ADMIN_TOKEN),
528+ Some(form),
529+ )
530+ .await;
531+ assert_eq!(status, 403);
532+ assert_eq!(fx.state.live().ci.max_log_mb, 16);
533+ }
534+
535+ #[tokio::test]
536+ async fn a_live_override_applies_at_once_and_reset_goes_back() {
537+ let fx = fixture().await;
538+ assert_eq!(fx.state.live().ci.max_log_mb, 16);
539+ let body = save(&fx, "limits", "ci.max_log_mb=99&ci.enabled=true").await;
540+ assert!(body.contains("Server settings saved."), "{body}");
541+ assert_eq!(fx.state.live().ci.max_log_mb, 99);
542+ let stored = fx.state.store.server_overrides().await.unwrap();
543+ assert_eq!(stored.get("ci.max_log_mb").map(String::as_str), Some("99"));
544+ assert!(
545+ !stored.contains_key("ci.enabled"),
546+ "unchanged fields are not stored"
547+ );
548+ let page = admin_get(&fx, "/admin/server?tab=limits").await;
549+ assert!(page.contains("Reset to file value"));
550+
551+ let form = format!("csrf={CSRF}&tab=limits&key=ci.max_log_mb");
552+ let (status, _, _) = send(
553+ &fx.router,
554+ "POST",
555+ "/admin/server/reset",
556+ Some(ADMIN_TOKEN),
557+ Some(form),
558+ )
559+ .await;
560+ assert_eq!(status, 303);
561+ assert_eq!(fx.state.live().ci.max_log_mb, 16);
562+ assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
563+ }
564+
565+ #[tokio::test]
566+ async fn live_registration_is_read_by_the_register_page() {
567+ let fx = fixture().await;
568+ let (closed, _, _) = send(&fx.router, "GET", "/register", None, None).await;
569+ assert_eq!(closed, 404);
570+ save(&fx, "general", "registration=open&orgs.creation=all").await;
571+ let (open, _, _) = send(&fx.router, "GET", "/register", None, None).await;
572+ assert_eq!(open, 200);
573+ }
574+
575+ #[tokio::test]
576+ async fn bad_values_are_rejected_and_nothing_is_stored() {
577+ let fx = fixture().await;
578+ for (tab, fields) in [
579+ ("general", "registration=everyone"),
580+ ("general", "trusted_proxies=not-an-ip"),
581+ ("limits", "ci.max_log_mb=0"),
582+ ("limits", "ci.max_log_mb=lots"),
583+ ("storage", "storage.backend=r2"),
584+ ("backups", "backup.keep=0&backup.dir=%2Fvar%2Fbackups"),
585+ ] {
586+ let body = save(&fx, tab, fields).await;
587+ assert!(!body.contains("Server settings saved."), "{fields}: {body}");
588+ assert!(
589+ fx.state.store.server_overrides().await.unwrap().is_empty(),
590+ "{fields}"
591+ );
592+ }
593+ assert_eq!(fx.state.live().ci.max_log_mb, 16);
594+ }
595+
596+ #[tokio::test]
597+ async fn a_restart_field_is_saved_but_waits_for_a_restart() {
598+ let fx = fixture().await;
599+ save(&fx, "general", "base_url=https%3A%2F%2Fnew.example").await;
600+ assert_eq!(
601+ fx.state
602+ .store
603+ .server_overrides()
604+ .await
605+ .unwrap()
606+ .get("base_url")
607+ .map(String::as_str),
608+ Some("https://new.example")
609+ );
610+ assert_eq!(fx.state.live().base_url, "https://forge.test/");
611+ let page = admin_get(&fx, "/admin/server?tab=general").await;
612+ assert!(page.contains("restart needed"));
613+ assert!(page.contains("https://new.example"));
614+ }
615+
616+ #[tokio::test]
617+ async fn read_only_fields_are_shown_and_cannot_be_posted() {
618+ let fx = fixture().await;
619+ let page = admin_get(&fx, "/admin/server?tab=general").await;
620+ assert!(page.contains("127.0.0.1:7660"));
621+ assert!(!page.contains("name=\"listen\""));
622+ save(&fx, "general", "listen=0.0.0.0%3A1").await;
623+ assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
624+ }
625+
626+ #[tokio::test]
627+ async fn secrets_are_never_rendered_and_are_stored_sealed() {
628+ let fx = fixture().await;
629+ let secret = "https://hc.example/ping/TOPSECRET-TOKEN";
630+ let body = save(
631+ &fx,
632+ "backups",
633+ &format!("backup.healthcheck_url={}", enc(secret)),
634+ )
635+ .await;
636+ assert!(body.contains("Server settings saved."), "{body}");
637+ for tab in ["backups", "general", "limits", "storage", "integrations"] {
638+ let page = admin_get(&fx, &format!("/admin/server?tab={tab}")).await;
639+ assert!(!page.contains("TOPSECRET"), "tab {tab}");
640+ }
641+ let page = admin_get(&fx, "/admin/server?tab=backups").await;
642+ assert!(page.contains("set"));
643+ // Stored sealed, readable only through the store with the instance key.
644+ let conn_value = fx.state.store.server_overrides().await.unwrap();
645+ assert_eq!(
646+ conn_value.get("backup.healthcheck_url").map(String::as_str),
647+ Some(secret)
648+ );
649+ // A blank post keeps it.
650+ save(&fx, "backups", "backup.healthcheck_url=").await;
651+ assert!(
652+ fx.state
653+ .store
654+ .server_overrides()
655+ .await
656+ .unwrap()
657+ .contains_key("backup.healthcheck_url")
658+ );
659+ // Reset removes it.
660+ let form = format!("csrf={CSRF}&tab=backups&key=backup.healthcheck_url");
661+ send(
662+ &fx.router,
663+ "POST",
664+ "/admin/server/reset",
665+ Some(ADMIN_TOKEN),
666+ Some(form),
667+ )
668+ .await;
669+ assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
670+ }
671+
672+ #[tokio::test]
673+ async fn saving_is_audited_without_values() {
674+ let fx = fixture().await;
675+ save(&fx, "limits", "ci.max_log_mb=77").await;
676+ let entries = fx
677+ .state
678+ .store
679+ .list_audit(&Default::default(), None, 50)
680+ .await
681+ .unwrap();
682+ let entry = entries
683+ .iter()
684+ .find(|e| e.action == AuditAction::ServerSettingsUpdated)
685+ .expect("audit entry");
686+ let text = format!("{entry:?}");
687+ assert!(text.contains("ci.max_log_mb"));
688+ assert!(!text.contains("77"));
689+ }
690+}
crates/forge-web/src/pages/invites.rsmodified+2 -2
@@ -81,7 +81,7 @@ async fn invites_submit(cx: &Cx, Form(form): Form<InviteForm>) -> Result<impl Vi
81 let address = form.email.trim().to_owned();81 let address = form.email.trim().to_owned();
82 let mut notice = None;82 let mut notice = None;
83 let mut error = None;83 let mut error = None;
84- if state.config.registration == Registration::Closed {84+ if state.live().registration == Registration::Closed {
85 error = Some(t(lang, Key::InvitesOff).to_owned());85 error = Some(t(lang, Key::InvitesOff).to_owned());
86 } else {86 } else {
87 match validate_email(&address) {87 match validate_email(&address) {
@@ -127,7 +127,7 @@ mod tests {
127 127
128 async fn app(dir: &Path) -> (topcoat::router::Router, AppState) {128 async fn app(dir: &Path) -> (topcoat::router::Router, AppState) {
129 let mut state = crate::test_support::test_state(dir).await;129 let mut state = crate::test_support::test_state(dir).await;
130- state.config = std::sync::Arc::new(forge_core::Config {130+ state.set_config(forge_core::Config {
131 registration: Registration::Invite,131 registration: Registration::Invite,
132 ..crate::test_support::test_config(dir)132 ..crate::test_support::test_config(dir)
133 });133 });
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -4,6 +4,7 @@ pub mod admin_backups;
4 pub mod admin_mail;4 pub mod admin_mail;
5 pub mod admin_replication;5 pub mod admin_replication;
6 pub mod admin_runners;6 pub mod admin_runners;
7+pub mod admin_server;
7 pub mod admin_users;8 pub mod admin_users;
8 pub mod archive;9 pub mod archive;
9 pub mod assets;10 pub mod assets;
crates/forge-web/src/pages/org_new.rsmodified+1 -1
@@ -33,7 +33,7 @@ struct NewOrgForm {
33 33
34 /// Whether `user` may create an organization under the instance's policy.34 /// Whether `user` may create an organization under the instance's policy.
35 fn may_create_org(state: &AppState, user: &User) -> bool {35 fn may_create_org(state: &AppState, user: &User) -> bool {
36- match state.config.orgs.creation {36+ match state.live().orgs.creation {
37 OrgCreation::All => true,37 OrgCreation::All => true,
38 OrgCreation::Admin => user.is_admin,38 OrgCreation::Admin => user.is_admin,
39 }39 }
crates/forge-web/src/pages/register.rsmodified+5 -6
@@ -184,7 +184,7 @@ async fn register_form(
184 #[page("/register")]184 #[page("/register")]
185 async fn register_page(cx: &Cx) -> Result<impl View> {185 async fn register_page(cx: &Cx) -> Result<impl View> {
186 let state = app_context::<AppState>(cx);186 let state = app_context::<AppState>(cx);
187- if state.config.registration == Registration::Closed {187+ if state.live().registration == Registration::Closed {
188 return Err(not_found().into());188 return Err(not_found().into());
189 }189 }
190 if current_user(cx).await?.is_some() {190 if current_user(cx).await?.is_some() {
@@ -198,7 +198,7 @@ async fn register_page(cx: &Cx) -> Result<impl View> {
198 "" => None,198 "" => None,
199 token => state.store.invite_email(token).await?,199 token => state.store.invite_email(token).await?,
200 };200 };
201- let gate = gate_for(&state.config.registration, &invite, invited_email.is_some());201+ let gate = gate_for(&state.live().registration, &invite, invited_email.is_some());
202 let invited = invited_email.is_some();202 let invited = invited_email.is_some();
203 let email = invited_email.unwrap_or_default();203 let email = invited_email.unwrap_or_default();
204 let lang = i18n::lang(cx, None);204 let lang = i18n::lang(cx, None);
@@ -265,7 +265,7 @@ async fn create_account(
265 #[page(POST "/register")]265 #[page(POST "/register")]
266 async fn register_submit(cx: &Cx, Form(form): Form<RegisterForm>) -> Result<impl View> {266 async fn register_submit(cx: &Cx, Form(form): Form<RegisterForm>) -> Result<impl View> {
267 let state = app_context::<AppState>(cx);267 let state = app_context::<AppState>(cx);
268- if state.config.registration == Registration::Closed {268+ if state.live().registration == Registration::Closed {
269 return Err(not_found().into());269 return Err(not_found().into());
270 }270 }
271 // Login CSRF: the pre-session token must match the cookie before anything else runs.271 // 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<RegisterForm>) -> Result<impl
287 "" => None,287 "" => None,
288 token => state.store.invite_email(token).await?,288 token => state.store.invite_email(token).await?,
289 };289 };
290- let gate = gate_for(&state.config.registration, &invite, invited_email.is_some());290+ let gate = gate_for(&state.live().registration, &invite, invited_email.is_some());
291 let mut error = None;291 let mut error = None;
292 if limited && gate == Gate::Form {292 if limited && gate == Gate::Form {
293 error = Some(t(lang, Key::ErrThrottled).to_owned());293 error = Some(t(lang, Key::ErrThrottled).to_owned());
@@ -509,14 +509,13 @@ mod tests {
509 use std::path::Path;509 use std::path::Path;
510 510
511 use forge_core::{Config, Registration};511 use forge_core::{Config, Registration};
512- use std::sync::Arc;
513 512
514 use super::test_helpers::{field_from, link_in, precsrf_for, send};513 use super::test_helpers::{field_from, link_in, precsrf_for, send};
515 use crate::state::AppState;514 use crate::state::AppState;
516 515
517 async fn app(dir: &Path, mode: Registration) -> (topcoat::router::Router, AppState) {516 async fn app(dir: &Path, mode: Registration) -> (topcoat::router::Router, AppState) {
518 let mut state = crate::test_support::test_state(dir).await;517 let mut state = crate::test_support::test_state(dir).await;
519- state.config = Arc::new(Config {518+ state.set_config(Config {
520 registration: mode,519 registration: mode,
521 ..crate::test_support::test_config(dir)520 ..crate::test_support::test_config(dir)
522 });521 });
crates/forge-web/src/pages/releases.rsmodified+1 -1
@@ -954,7 +954,7 @@ async fn edit_parts(
954 links,954 links,
955 delete_actions,955 delete_actions,
956 upload_action: format!("/{title}/releases/{}/assets", enc(&release.id)),956 upload_action: format!("/{title}/releases/{}/assets", enc(&release.id)),
957- upload_hint: g::upload_hint(lang, state.config.releases.max_asset_mb),957+ upload_hint: g::upload_hint(lang, state.live().releases.max_asset_mb),
958 delete_href: format!("/{title}/releases/{}/delete", enc(&release.id)),958 delete_href: format!("/{title}/releases/{}/delete", enc(&release.id)),
959 view_tag: tag_href(&title, &release.tag),959 view_tag: tag_href(&title, &release.tag),
960 action: release_edit_href(&title, &release.id),960 action: release_edit_href(&title, &release.id),
crates/forge-web/src/pages/releases_tests.rsmodified+1 -2
@@ -2,7 +2,6 @@
2 //! download counter, the size cap and deletion. Each test runs against a real bare repo.2 //! download counter, the size cap and deletion. Each test runs against a real bare repo.
3 3
4 use std::path::{Path, PathBuf};4 use std::path::{Path, PathBuf};
5-use std::sync::Arc;
6 5
7 use forge_core::releases::Release;6 use forge_core::releases::Release;
8 use forge_core::{Repo, Role, Store, User, Visibility};7 use forge_core::{Repo, Role, Store, User, Visibility};
@@ -120,7 +119,7 @@ async fn fixture(max_mb: Option<u64>) -> Fixture {
120 if let Some(mb) = max_mb {119 if let Some(mb) = max_mb {
121 let mut config = (*state.config).clone();120 let mut config = (*state.config).clone();
122 config.releases.max_asset_mb = mb;121 config.releases.max_asset_mb = mb;
123- state.config = Arc::new(config);122+ state.set_config(config);
124 }123 }
125 let store = state.store.clone();124 let store = state.store.clone();
126 let tahinli = store125 let tahinli = store
crates/forge-web/src/pages/settings_security.rsmodified+3 -1
@@ -1048,8 +1048,10 @@ mod tests {
1048 orgs: Default::default(),1048 orgs: Default::default(),
1049 self_update: Default::default(),1049 self_update: Default::default(),
1050 };1050 };
1051+ let config = Arc::new(config);
1051 let state = AppState {1052 let state = AppState {
1052- config: Arc::new(config),1053+ settings: crate::state::settings_for(&config),
1054+ config,
1053 store: store.clone(),1055 store: store.clone(),
1054 git: Arc::new(GitEnv {1056 git: Arc::new(GitEnv {
1055 git_bin: "git".into(),1057 git_bin: "git".into(),
crates/forge-web/src/state.rsmodified+29 -0
@@ -11,7 +11,11 @@ use crate::throttle::Throttle;
11 11
12 #[derive(Clone)]12 #[derive(Clone)]
13 pub struct AppState {13 pub struct AppState {
14+ /// The config the process booted with: the file plus every stored override. Live settings
15+ /// can differ from it, so read those through `live()`.
14 pub config: Arc<Config>,16 pub config: Arc<Config>,
17+ /// The admin-editable settings layer: file config, boot config and the live view.
18+ pub settings: Arc<forge_core::server_settings::Live>,
15 pub store: Store,19 pub store: Store,
16 pub git: Arc<GitEnv>,20 pub git: Arc<GitEnv>,
17 /// Instance secret key (data_dir/forge.key). Signs private raw-file URLs.21 /// Instance secret key (data_dir/forge.key). Signs private raw-file URLs.
@@ -46,3 +50,28 @@ pub struct AppState {
46 /// Change counters of CI jobs and runs. Log followers and run pages wait on them.50 /// Change counters of CI jobs and runs. Log followers and run pages wait on them.
47 pub ci_live: Arc<crate::ci::CiLive>,51 pub ci_live: Arc<crate::ci::CiLive>,
48 }52 }
53+
54+/// A settings handle over `config` with no stored overrides and no file keys. For tests.
55+#[cfg(test)]
56+pub fn settings_for(config: &Arc<Config>) -> Arc<forge_core::server_settings::Live> {
57+ Arc::new(forge_core::server_settings::Live::new(
58+ config.clone(),
59+ Default::default(),
60+ config.clone(),
61+ ))
62+}
63+
64+impl AppState {
65+ /// The config the running process uses now: `config` with the live settings applied. Take it
66+ /// once per request or pass; a later save does not change a value already read.
67+ pub fn live(&self) -> Arc<Config> {
68+ self.settings.current()
69+ }
70+
71+ /// Replaces the config and resets the settings layer over it. For tests.
72+ #[cfg(test)]
73+ pub fn set_config(&mut self, config: Config) {
74+ self.config = Arc::new(config);
75+ self.settings = settings_for(&self.config);
76+ }
77+}
crates/forge-web/src/test_support.rsmodified+3 -1
@@ -60,8 +60,10 @@ pub fn test_config(dir: &Path) -> Config {
60 pub async fn test_state(dir: &Path) -> AppState {60 pub async fn test_state(dir: &Path) -> AppState {
61 let store = Store::open(&dir.join("forge.db")).await.unwrap();61 let store = Store::open(&dir.join("forge.db")).await.unwrap();
62 store.set_secret_key(KEY);62 store.set_secret_key(KEY);
63+ let config = Arc::new(test_config(dir));
63 AppState {64 AppState {
64- config: Arc::new(test_config(dir)),65+ settings: crate::state::settings_for(&config),
66+ config,
65 store,67 store,
66 git: Arc::new(GitEnv {68 git: Arc::new(GitEnv {
67 git_bin: "git".into(),69 git_bin: "git".into(),
crates/forge-web/src/views/mod.rsmodified+9 -0
@@ -476,6 +476,12 @@ fn admin_items(lang: Lang) -> Vec<NavItem> {
476 "runners",476 "runners",
477 ),477 ),
478 item("mail", "/admin/mail", ad::t(lang, AK::Mail), "mail"),478 item("mail", "/admin/mail", ad::t(lang, AK::Mail), "mail"),
479+ item(
480+ "server",
481+ "/admin/server",
482+ ad::t(lang, AK::ServerSettings),
483+ "server",
484+ ),
479 item(485 item(
480 "backups",486 "backups",
481 "/admin/backups",487 "/admin/backups",
@@ -662,6 +668,9 @@ async fn nav_icon(name: &str) -> Result<impl View> {
662 if name == "mail" {668 if name == "mail" {
663 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/></svg>669 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/></svg>
664 }670 }
671+ if name == "server" {
672+ <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h10M18 6h2M4 12h2M10 12h10M4 18h12M20 18h0"/><circle cx="16" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="18" cy="18" r="2"/></svg>
673+ }
665 if name == "backups" {674 if name == "backups" {
666 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5"/><path d="M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"/></svg>675 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><ellipse cx="12" cy="5" rx="8" ry="3"/><path d="M4 5v6c0 1.7 3.6 3 8 3s8-1.3 8-3V5"/><path d="M4 11v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"/></svg>
667 }676 }
crates/forge-web/tests/section_nav_e2e.rsmodified+1 -0
@@ -285,6 +285,7 @@ async fn admin_pages_get_the_admin_sidebar() {
285 "/admin/audit",285 "/admin/audit",
286 "/admin/runners",286 "/admin/runners",
287 "/admin/mail",287 "/admin/mail",
288+ "/admin/server",
288 "/admin/backups",289 "/admin/backups",
289 "/admin/replication",290 "/admin/replication",
290 ];291 ];
docs/architecture.mdmodified+14 -0
@@ -320,6 +320,20 @@ Written at boot by `write_managed_gitconfig()`. Keys:
320 - 2.38 is required for `merge-tree --write-tree`.320 - 2.38 is required for `merge-tree --write-tree`.
321 - 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).321 - 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).
322 322
323+### 7.6 Server settings (`/admin/server`)
324+
325+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.
326+
327+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.
328+
329+Each field has a kind:
330+
331+- **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.
332+- **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.
333+- **read-only**: listen addresses, database path and data dir. Shown, never editable.
334+
335+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.
336+
323 ---337 ---
324 338
325 ## 8. Data safety and reliability339 ## 8. Data safety and reliability
docs/ci.mdmodified+23 -1
@@ -411,7 +411,14 @@ jobs are running, the runner stops claiming, replaces its binary, and exits with
411 restarts it. It is skipped when the forge's binary is for a different OS or architecture. Set411 restarts it. It is skipped when the forge's binary is for a different OS or architecture. Set
412 `auto_update = false` to pin the binary by hand.412 `auto_update = false` to pin the binary by hand.
413 413
414-`concurrency` is the number of jobs run in parallel. The default is 1. Jobs without `needs` between414+`concurrency` is the number of jobs run in parallel. The default is 1. An admin can change it per runner
415+on the runners page (`/admin/runners`) with no restart: type a number from 1 to 64 and save. The
416+runner picks it up on its next claim or job heartbeat, grows or shrinks its job slots, and logs
417+`runner: concurrency 1 -> 2 (set from server)`. Lowering it never kills a running job; the extra
418+slots retire as those jobs finish. The precedence is the UI value first, then `runner.toml`. "Use
419+runner.toml value" removes the UI value and the runner goes back to its file. The page also shows
420+the jobs running now, the last contact, and the runner's version, CPU count and memory, to help
421+choose a number. Jobs without `needs` between
415 them (for example `test` and `build` in this repo's own `ci.toml`) only run at the same time when the422 them (for example `test` and `build` in this repo's own `ci.toml`) only run at the same time when the
416 forge has capacity for both: set `concurrency = 2` on the runner or register a second runner.423 forge has capacity for both: set `concurrency = 2` on the runner or register a second runner.
417 Otherwise they queue and run one after the other. Each concurrent job needs its own RAM, so a424 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
419 capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp426 capabilities and `no_new_privileges`. The builtin executor also runs each job under a seccomp
420 profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`.427 profile that denies calls such as `mount`, `ptrace`, `bpf` and `unshare`.
421 428
429+Every `runner.toml` field is visible on the runner's page (`/admin/runners/<id>`), with its value and
430+whether it comes from `runner.toml` or the UI. The runner reports its effective config when it
431+starts, with the secret and registry passwords left out. Fields come in three kinds:
432+
433+- Live: `concurrency` and `labels`, applied on the runner's next check-in.
434+- Restart needed: `auto_update`, `executor`, `work_dir`, `sandbox.userns`, the `limits.*` values,
435+ `images.keep_days` and `cache_max_gib`. The forge stores the value now and the runner applies it to
436+ its in-memory config when it next starts, so `runner.toml` on disk is never rewritten. The row says
437+ "restart needed" until the runner has started with it.
438+- Read-only: `name`, `url`, `runner_id`, `runner_secret` and `registry`, because changing them from the
439+ forge could lock the runner out.
440+
441+A UI value beats `runner.toml` and "Use runner.toml value" clears it. Old runners and old forges still
442+work together: an old runner just never reports, and an old forge never sends overrides.
443+
422 Image garbage collection runs at startup and then daily. Unpacked images are kept under444 Image garbage collection runs at startup and then daily. Unpacked images are kept under
423 `work_dir/oci`.445 `work_dir/oci`.
424 446
style/main.scssmodified+116 -0
@@ -4005,6 +4005,44 @@ span.reaction {
4005 white-space: nowrap;4005 white-space: nowrap;
4006 }4006 }
4007 4007
4008+// Runner concurrency and config forms: a compact input with its buttons on one line.
4009+.runner-conc-form {
4010+ display: flex;
4011+ align-items: center;
4012+ gap: 8px;
4013+ margin: 0;
4014+
4015+ input[type="number"] {
4016+ width: 5.5rem;
4017+ }
4018+
4019+ input,
4020+ select,
4021+ button {
4022+ height: var(--control-h);
4023+ margin: 0;
4024+ }
4025+}
4026+
4027+.runner-source {
4028+ white-space: nowrap;
4029+}
4030+
4031+.runner-facts {
4032+ display: grid;
4033+ grid-template-columns: max-content 1fr;
4034+ gap: 4px 16px;
4035+ margin: 0;
4036+
4037+ dt {
4038+ color: var(--muted);
4039+ }
4040+
4041+ dd {
4042+ margin: 0;
4043+ }
4044+}
4045+
4008 .ci-state.runner-disabled {4046 .ci-state.runner-disabled {
4009 background: var(--code-bg);4047 background: var(--code-bg);
4010 color: var(--muted);4048 color: var(--muted);
@@ -5676,3 +5714,81 @@ span.reaction {
5676 min-width: 0;5714 min-width: 0;
5677 }5715 }
5678 }5716 }
5717+
5718+// Server settings page (/admin/server): a grid of field cells that fits a tab in the viewport.
5719+.srv-grid {
5720+ display: grid;
5721+ grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr));
5722+ gap: 16px 24px;
5723+}
5724+
5725+.srv-field {
5726+ display: flex;
5727+ flex-direction: column;
5728+ gap: 6px;
5729+ min-width: 0;
5730+
5731+ p {
5732+ margin: 0;
5733+ }
5734+
5735+ input[type="text"],
5736+ input[type="number"],
5737+ input[type="password"],
5738+ select {
5739+ width: 100%;
5740+ }
5741+}
5742+
5743+.srv-head {
5744+ display: flex;
5745+ flex-wrap: wrap;
5746+ align-items: center;
5747+ gap: 4px;
5748+
5749+ .badge {
5750+ margin-left: 0;
5751+ }
5752+}
5753+
5754+.srv-label {
5755+ font-weight: 500;
5756+ font-size: 0.875rem;
5757+ color: var(--text-2);
5758+ margin-right: 4px;
5759+}
5760+
5761+.badge {
5762+ &.srv-live {
5763+ background: var(--public-bg);
5764+ color: var(--public-text);
5765+ }
5766+
5767+ &.srv-restart,
5768+ &.srv-ro,
5769+ &.srv-source {
5770+ background: var(--private-bg);
5771+ color: var(--private-text);
5772+ border-color: var(--border-strong);
5773+ }
5774+
5775+ &.srv-pending {
5776+ color: var(--warn);
5777+ border-color: var(--warn);
5778+ }
5779+}
5780+
5781+.srv-fixed {
5782+ overflow-wrap: anywhere;
5783+}
5784+
5785+.srv-reset {
5786+ display: flex;
5787+ flex-wrap: wrap;
5788+ align-items: center;
5789+ gap: 8px;
5790+}
5791+
5792+.srv-form .actions {
5793+ margin-top: 16px;
5794+}