Forge-runner and forge-web-base drop dead code, duplicated parsing and stale comments
Browse files at this commit68935b01378832035d4c49610dd2dc802e338416Parent: e587be7- refactor
- forge-runner and forge-web-base drop dead code, duplicated parsing and stale comments
- fixes: memory.high no longer drops to 0 on small boxes, log lines are cut at MAX_LINE exactly, a half-installed image rootfs is replaced on retry, register resolves local paths before using the one-time token, strip_ansi keeps the char after a lone ESC
65 changed files +490 -1489
- crates/forge-ci/src/proto.rs +17 -0
- crates/forge-runner/src/artifacts.rs +5 -10
- crates/forge-runner/src/cli.rs +5 -28
- crates/forge-runner/src/client.rs +26 -55
- crates/forge-runner/src/config.rs +17 -54
- crates/forge-runner/src/executor.rs +0 -104
- crates/forge-runner/src/lib.rs +12 -13
- crates/forge-runner/src/logs.rs +5 -3
- crates/forge-runner/src/memory.rs +41 -64
- crates/forge-runner/src/metrics.rs +2 -17
- crates/forge-runner/src/oci/pull.rs +5 -18
- crates/forge-runner/src/oci/store.rs +14 -6
- crates/forge-runner/src/pressure.rs +30 -57
- crates/forge-runner/src/runner.rs +11 -75
- crates/forge-runner/src/sandbox/exec.rs +5 -7
- crates/forge-runner/src/sandbox/helper.rs +0 -22
- crates/forge-runner/src/sandbox/idmap.rs +28 -33
- crates/forge-runner/src/sandbox/spec.rs +42 -88
- crates/forge-runner/src/selflog.rs +6 -25
- crates/forge-runner/src/update.rs +2 -2
- crates/forge-runner/src/workspace.rs +1 -14
- crates/forge-runner/tests/integration/flow.rs +24 -30
- crates/forge-runner/tests/integration/idmap.rs +6 -3
- crates/forge-runner/tests/integration/sandbox.rs +4 -103
- crates/forge-runner/tests/integration/unpack_subuid.rs +5 -21
- crates/forge-web-account/src/pages/settings_live.rs +3 -3
- crates/forge-web-app/src/alerts.rs +1 -1
- crates/forge-web-app/src/ci/runner_log.rs +4 -18
- crates/forge-web-app/src/self_update.rs +1 -2
- crates/forge-web-app/src/views/mod.rs +12 -14
- crates/forge-web-base/src/accent.rs +2 -65
- crates/forge-web-base/src/blobs.rs +34 -38
- crates/forge-web-base/src/custom_colour.rs +3 -26
- crates/forge-web-base/src/i18n/accounts.rs +0 -6
- crates/forge-web-base/src/i18n/alerts.rs +2 -11
- crates/forge-web-base/src/i18n/authoring.rs +0 -3
- crates/forge-web-base/src/i18n/browse.rs +0 -10
- crates/forge-web-base/src/i18n/code.rs +3 -15
- crates/forge-web-base/src/i18n/community.rs +1 -38
- crates/forge-web-base/src/i18n/integrations.rs +0 -24
- crates/forge-web-base/src/i18n/issues.rs +2 -59
- crates/forge-web-base/src/i18n/mod.rs +9 -4
- crates/forge-web-base/src/i18n/pulls.rs +0 -30
- crates/forge-web-base/src/i18n/pulls_review.rs +0 -114
- crates/forge-web-base/src/i18n/push.rs +1 -0
- crates/forge-web-base/src/i18n/releases_ci.rs +0 -17
- crates/forge-web-base/src/i18n/repo_admin.rs +0 -4
- crates/forge-web-base/src/render/highlight.rs +2 -5
- crates/forge-web-base/src/render/markdown.rs +4 -15
- crates/forge-web-base/src/repo_stats.rs +0 -31
- crates/forge-web-base/src/theme.rs +46 -54
- crates/forge-web-base/src/throttle.rs +21 -11
- crates/forge-web-pages/src/pages/ci_runs.rs +1 -1
- crates/forge-web-pages/src/pages/finder.rs +1 -1
- crates/forge-web-pages/src/pages/issues_list.rs +12 -5
- crates/forge-web-pages/src/pages/notifications.rs +1 -1
- crates/forge-web-pages/src/pages/repo.rs +2 -2
- crates/forge-web-pages/src/pages/repo_mirrors.rs +1 -1
- crates/forge-web-repo/src/pages/commits.rs +1 -1
- crates/forge-web-repo/src/pages/discussion_view.rs +1 -1
- crates/forge-web-repo/src/pages/discussions.rs +1 -1
- crates/forge-web-repo/src/pages/labels_page.rs +1 -1
- crates/forge-web-repo/src/pages/milestones_page.rs +2 -2
- crates/forge-web-repo/src/pages/pulls_list.rs +1 -1
- crates/forge-web-repo/src/pages/repo_webhooks.rs +1 -1
crates/forge-ci/src/proto.rsmodified+17 -0
| @@ -8,6 +8,8 @@ use std::fmt; | |||
| 8 | 8 | ||
| 9 | use serde::{Deserialize, Serialize}; | 9 | use serde::{Deserialize, Serialize}; |
| 10 | 10 | ||
| 11 | +pub const RESTART_EXIT_CODE: u8 = 75; | ||
| 12 | + | ||
| 11 | /// `POST /api/v1/ci/runners/register` | 13 | /// `POST /api/v1/ci/runners/register` |
| 12 | #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] | 14 | #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 13 | pub struct RegisterRequest { | 15 | pub struct RegisterRequest { |
| @@ -122,6 +124,21 @@ pub struct RunnerLogLine { | |||
| 122 | pub text: String, | 124 | pub text: String, |
| 123 | } | 125 | } |
| 124 | 126 | ||
| 127 | +/// Longest text kept for one runner log line, in bytes. | ||
| 128 | +pub const RUNNER_LOG_MAX_TEXT: usize = 4096; | ||
| 129 | + | ||
| 130 | +/// `text` cut to at most `max` bytes, on a character boundary. | ||
| 131 | +pub fn truncate_text(text: &str, max: usize) -> &str { | ||
| 132 | + if text.len() <= max { | ||
| 133 | + return text; | ||
| 134 | + } | ||
| 135 | + let mut end = max; | ||
| 136 | + while !text.is_char_boundary(end) { | ||
| 137 | + end -= 1; | ||
| 138 | + } | ||
| 139 | + &text[..end] | ||
| 140 | +} | ||
| 141 | + | ||
| 125 | /// The answer to a [`RunnerLogBatch`]: the number of the next line the forge wants for this boot | 142 | /// The answer to a [`RunnerLogBatch`]: the number of the next line the forge wants for this boot |
| 126 | /// id. A forge that restarted (or never saw this boot id) answers 0 and the runner resends what it | 143 | /// id. A forge that restarted (or never saw this boot id) answers 0 and the runner resends what it |
| 127 | /// still holds; lines it no longer holds are skipped. | 144 | /// still holds; lines it no longer holds are skipped. |
crates/forge-runner/src/artifacts.rsmodified+5 -10
| @@ -11,9 +11,9 @@ use std::path::{Path, PathBuf}; | |||
| 11 | use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; | 11 | use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; |
| 12 | 12 | ||
| 13 | /// The server accepts names matching `[A-Za-z0-9._+-]{1,128}` and not starting with `.`. | 13 | /// The server accepts names matching `[A-Za-z0-9._+-]{1,128}` and not starting with `.`. |
| 14 | -pub const MAX_NAME_LEN: usize = 128; | 14 | +const MAX_NAME_LEN: usize = 128; |
| 15 | /// The server caps artifacts per job at 50 by default. | 15 | /// The server caps artifacts per job at 50 by default. |
| 16 | -pub const MAX_FILES: usize = 50; | 16 | +const MAX_FILES: usize = 50; |
| 17 | 17 | ||
| 18 | /// Errors from collecting artifacts. Any of them fails the job. | 18 | /// Errors from collecting artifacts. Any of them fails the job. |
| 19 | #[derive(Debug, thiserror::Error)] | 19 | #[derive(Debug, thiserror::Error)] |
| @@ -41,12 +41,11 @@ pub struct Artifact { | |||
| 41 | pub name: String, | 41 | pub name: String, |
| 42 | /// The file on disk, inside the workspace. | 42 | /// The file on disk, inside the workspace. |
| 43 | pub path: PathBuf, | 43 | pub path: PathBuf, |
| 44 | - pub size: u64, | ||
| 45 | } | 44 | } |
| 46 | 45 | ||
| 47 | /// Turns a workspace-relative path into one upload name: `/` becomes `_`, characters outside | 46 | /// Turns a workspace-relative path into one upload name: `/` becomes `_`, characters outside |
| 48 | /// the server alphabet become `_`, and a leading `.` is replaced so the name is never hidden. | 47 | /// the server alphabet become `_`, and a leading `.` is replaced so the name is never hidden. |
| 49 | -pub fn flatten_name(rel: &str) -> Result<String, ArtifactError> { | 48 | +fn flatten_name(rel: &str) -> Result<String, ArtifactError> { |
| 50 | let joined = rel | 49 | let joined = rel |
| 51 | .split('/') | 50 | .split('/') |
| 52 | .filter(|c| !c.is_empty()) | 51 | .filter(|c| !c.is_empty()) |
| @@ -72,7 +71,7 @@ pub fn flatten_name(rel: &str) -> Result<String, ArtifactError> { | |||
| 72 | } | 71 | } |
| 73 | 72 | ||
| 74 | /// Rejects patterns that are absolute or climb out of the workspace. | 73 | /// Rejects patterns that are absolute or climb out of the workspace. |
| 75 | -pub fn check_pattern(pattern: &str) -> Result<(), ArtifactError> { | 74 | +fn check_pattern(pattern: &str) -> Result<(), ArtifactError> { |
| 76 | let bad = | 75 | let bad = |
| 77 | pattern.is_empty() || pattern.starts_with('/') || pattern.split('/').any(|c| c == ".."); | 76 | pattern.is_empty() || pattern.starts_with('/') || pattern.split('/').any(|c| c == ".."); |
| 78 | if bad { | 77 | if bad { |
| @@ -161,11 +160,7 @@ pub fn collect( | |||
| 161 | limit: max_bytes_per_file, | 160 | limit: max_bytes_per_file, |
| 162 | }); | 161 | }); |
| 163 | } | 162 | } |
| 164 | - out.push(Artifact { | 163 | + out.push(Artifact { name, path: real }); |
| 165 | - name, | ||
| 166 | - path: real, | ||
| 167 | - size: meta.len(), | ||
| 168 | - }); | ||
| 169 | } | 164 | } |
| 170 | Ok(out) | 165 | Ok(out) |
| 171 | } | 166 | } |
crates/forge-runner/src/cli.rsmodified+5 -28
| @@ -108,9 +108,6 @@ where | |||
| 108 | return ExitCode::FAILURE; | 108 | return ExitCode::FAILURE; |
| 109 | } | 109 | } |
| 110 | }; | 110 | }; |
| 111 | - // Another subscriber may already be installed, for example by forge-web. Keep that one. | ||
| 112 | - // The env filter applies to the terminal output only. The runner's own log that is shipped to | ||
| 113 | - // the forge is always INFO and above, whatever the env filter says, see `selflog`. | ||
| 114 | let _ = tracing_subscriber::registry() | 111 | let _ = tracing_subscriber::registry() |
| 115 | .with( | 112 | .with( |
| 116 | tracing_subscriber::fmt::layer() | 113 | tracing_subscriber::fmt::layer() |
| @@ -190,6 +187,8 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 190 | config: path, | 187 | config: path, |
| 191 | work_dir, | 188 | work_dir, |
| 192 | } => { | 189 | } => { |
| 190 | + let path = path.map_or_else(config::default_config_path, Ok)?; | ||
| 191 | + let work_dir = work_dir.map_or_else(config::default_work_dir, Ok)?; | ||
| 193 | let client = ForgeClient::new(&url)?; | 192 | let client = ForgeClient::new(&url)?; |
| 194 | let resp = client | 193 | let resp = client |
| 195 | .register(&RegisterRequest { | 194 | .register(&RegisterRequest { |
| @@ -198,14 +197,6 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 198 | labels: labels.clone(), | 197 | labels: labels.clone(), |
| 199 | }) | 198 | }) |
| 200 | .await?; | 199 | .await?; |
| 201 | - let path = match path { | ||
| 202 | - Some(p) => p, | ||
| 203 | - None => config::default_config_path()?, | ||
| 204 | - }; | ||
| 205 | - let work_dir = match work_dir { | ||
| 206 | - Some(w) => w, | ||
| 207 | - None => config::default_work_dir()?, | ||
| 208 | - }; | ||
| 209 | let cfg = RunnerConfig { | 200 | let cfg = RunnerConfig { |
| 210 | url, | 201 | url, |
| 211 | runner_id: resp.runner_id.clone(), | 202 | runner_id: resp.runner_id.clone(), |
| @@ -231,15 +222,10 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 231 | Ok(ExitCode::SUCCESS) | 222 | Ok(ExitCode::SUCCESS) |
| 232 | } | 223 | } |
| 233 | Command::Run { config: path } => { | 224 | Command::Run { config: path } => { |
| 234 | - let path = match path { | 225 | + let path = path.map_or_else(config::default_config_path, Ok)?; |
| 235 | - Some(p) => p, | ||
| 236 | - None => config::default_config_path()?, | ||
| 237 | - }; | ||
| 238 | let mut cfg = config::load(&path)?; | 226 | let mut cfg = config::load(&path)?; |
| 239 | sync_config_with_forge(&mut cfg).await; | 227 | sync_config_with_forge(&mut cfg).await; |
| 240 | let shutdown = CancellationToken::new(); | 228 | let shutdown = CancellationToken::new(); |
| 241 | - // Only the builtin executor puts its jobs under the box. With the box, a lone job may | ||
| 242 | - // use all of it, so an undeclared job's cgroup limit is the box budget. | ||
| 243 | let pressure = match cfg.executor { | 229 | let pressure = match cfg.executor { |
| 244 | ExecutorKind::Builtin => { | 230 | ExecutorKind::Builtin => { |
| 245 | let budget = crate::memory::MemoryGate::for_host(&cfg.limits).ram_budget(); | 231 | let budget = crate::memory::MemoryGate::for_host(&cfg.limits).ram_budget(); |
| @@ -253,14 +239,12 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 253 | }; | 239 | }; |
| 254 | let cache_root = cfg.work_dir.join(".cache"); | 240 | let cache_root = cfg.work_dir.join(".cache"); |
| 255 | let cache_cap = cfg.cache_max_gib; | 241 | let cache_cap = cfg.cache_max_gib; |
| 256 | - // The id map is what the executor's jobs run under. The cache removes its dirs with it. | ||
| 257 | let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor { | 242 | let (executor, map): (Arc<dyn Executor>, IdMap) = match cfg.executor { |
| 258 | ExecutorKind::Podman => ( | 243 | ExecutorKind::Podman => ( |
| 259 | Arc::new(PodmanExecutor::new(cfg.limits.clone())), | 244 | Arc::new(PodmanExecutor::new(cfg.limits.clone())), |
| 260 | IdMap::single(), | 245 | IdMap::single(), |
| 261 | ), | 246 | ), |
| 262 | ExecutorKind::Builtin => { | 247 | ExecutorKind::Builtin => { |
| 263 | - // Resolved once. In subuid mode a failure here is a startup error. | ||
| 264 | let map = IdMap::resolve(cfg.sandbox.userns)?; | 248 | let map = IdMap::resolve(cfg.sandbox.userns)?; |
| 265 | tracing::info!("sandbox ids: {}", map.describe()); | 249 | tracing::info!("sandbox ids: {}", map.describe()); |
| 266 | let helper = std::env::current_exe()?; | 250 | let helper = std::env::current_exe()?; |
| @@ -275,7 +259,6 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 275 | let images = ImageStore::new(root) | 259 | let images = ImageStore::new(root) |
| 276 | .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) | 260 | .with_max_unpacked_bytes(gib(cfg.limits.image_max_gb)) |
| 277 | .with_idmap(map.clone(), helper.clone()); | 261 | .with_idmap(map.clone(), helper.clone()); |
| 278 | - // Before the first job: what an earlier run left behind. | ||
| 279 | crate::executor::sweep_leftovers(&cfg.work_dir, &map, &helper).await; | 262 | crate::executor::sweep_leftovers(&cfg.work_dir, &map, &helper).await; |
| 280 | let jobs_dir = cfg.work_dir.join("jobs"); | 263 | let jobs_dir = cfg.work_dir.join("jobs"); |
| 281 | let executor = | 264 | let executor = |
| @@ -304,20 +287,14 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> { | |||
| 304 | }); | 287 | }); |
| 305 | match runner.run(shutdown).await { | 288 | match runner.run(shutdown).await { |
| 306 | RunEnd::Stopped => Ok(ExitCode::SUCCESS), | 289 | RunEnd::Stopped => Ok(ExitCode::SUCCESS), |
| 307 | - // systemd restarts the runner on this code, and it starts the new binary. | 290 | + RunEnd::Updated | RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), |
| 308 | - RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), | ||
| 309 | - // An admin asked for a restart. The same exit code, the same systemd restart. | ||
| 310 | - RunEnd::Restart => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), | ||
| 311 | } | 291 | } |
| 312 | } | 292 | } |
| 313 | Command::Check { | 293 | Command::Check { |
| 314 | work_dir, | 294 | work_dir, |
| 315 | config: config_path, | 295 | config: config_path, |
| 316 | } => { | 296 | } => { |
| 317 | - let work_dir = match work_dir { | 297 | + let work_dir = work_dir.map_or_else(config::default_work_dir, Ok)?; |
| 318 | - Some(w) => w, | ||
| 319 | - None => config::default_work_dir()?, | ||
| 320 | - }; | ||
| 321 | let mode = check_userns_mode(config_path)?; | 298 | let mode = check_userns_mode(config_path)?; |
| 322 | let helper = std::env::current_exe()?; | 299 | let helper = std::env::current_exe()?; |
| 323 | if crate::check::run(&helper, &work_dir, mode).await { | 300 | if crate::check::run(&helper, &work_dir, mode).await { |
crates/forge-runner/src/client.rsmodified+26 -55
| @@ -172,27 +172,20 @@ impl ForgeClient { | |||
| 172 | .send() | 172 | .send() |
| 173 | .await?; | 173 | .await?; |
| 174 | let binary_sha256 = advertised_sha256(resp.headers()); | 174 | let binary_sha256 = advertised_sha256(resp.headers()); |
| 175 | - let concurrency = advertised_concurrency(resp.headers()); | 175 | + let mut reply = ClaimReply { |
| 176 | - let restart = advertised_restart(resp.headers()); | 176 | + job: None, |
| 177 | - let memory_budget = header_text(resp.headers(), MEMORY_BUDGET_HEADER); | 177 | + binary_sha256, |
| 178 | - let reserve_memory = header_text(resp.headers(), RESERVE_MEMORY_HEADER); | 178 | + concurrency: advertised_concurrency(resp.headers()), |
| 179 | + restart: advertised_restart(resp.headers()), | ||
| 180 | + memory_budget: header_text(resp.headers(), MEMORY_BUDGET_HEADER), | ||
| 181 | + reserve_memory: header_text(resp.headers(), RESERVE_MEMORY_HEADER), | ||
| 182 | + }; | ||
| 179 | match resp.status() { | 183 | match resp.status() { |
| 180 | - StatusCode::NO_CONTENT => Ok(ClaimReply { | 184 | + StatusCode::NO_CONTENT => Ok(reply), |
| 181 | - job: None, | 185 | + status if status.is_success() => { |
| 182 | - binary_sha256, | 186 | + reply.job = Some(resp.json().await?); |
| 183 | - concurrency, | 187 | + Ok(reply) |
| 184 | - restart, | 188 | + } |
| 185 | - memory_budget, | ||
| 186 | - reserve_memory, | ||
| 187 | - }), | ||
| 188 | - status if status.is_success() => Ok(ClaimReply { | ||
| 189 | - job: Some(resp.json().await?), | ||
| 190 | - binary_sha256, | ||
| 191 | - concurrency, | ||
| 192 | - restart, | ||
| 193 | - memory_budget, | ||
| 194 | - reserve_memory, | ||
| 195 | - }), | ||
| 196 | _ => Err(status_error(resp).await), | 189 | _ => Err(status_error(resp).await), |
| 197 | } | 190 | } |
| 198 | } | 191 | } |
| @@ -261,11 +254,7 @@ impl ForgeClient { | |||
| 261 | .timeout(REQUEST_TIMEOUT) | 254 | .timeout(REQUEST_TIMEOUT) |
| 262 | .send() | 255 | .send() |
| 263 | .await?; | 256 | .await?; |
| 264 | - if resp.status().is_success() { | 257 | + empty_or_error(resp).await |
| 265 | - Ok(()) | ||
| 266 | - } else { | ||
| 267 | - Err(status_error(resp).await) | ||
| 268 | - } | ||
| 269 | } | 258 | } |
| 270 | 259 | ||
| 271 | /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the | 260 | /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the |
| @@ -379,11 +368,7 @@ impl ForgeClient { | |||
| 379 | .timeout(ARTIFACT_TIMEOUT) | 368 | .timeout(ARTIFACT_TIMEOUT) |
| 380 | .send() | 369 | .send() |
| 381 | .await?; | 370 | .await?; |
| 382 | - if resp.status().is_success() { | 371 | + empty_or_error(resp).await |
| 383 | - Ok(()) | ||
| 384 | - } else { | ||
| 385 | - Err(status_error(resp).await) | ||
| 386 | - } | ||
| 387 | } | 372 | } |
| 388 | 373 | ||
| 389 | /// `POST /api/v1/ci/jobs/{id}/finish`. | 374 | /// `POST /api/v1/ci/jobs/{id}/finish`. |
| @@ -401,11 +386,7 @@ impl ForgeClient { | |||
| 401 | .timeout(REQUEST_TIMEOUT) | 386 | .timeout(REQUEST_TIMEOUT) |
| 402 | .send() | 387 | .send() |
| 403 | .await?; | 388 | .await?; |
| 404 | - if resp.status().is_success() { | 389 | + empty_or_error(resp).await |
| 405 | - Ok(()) | ||
| 406 | - } else { | ||
| 407 | - Err(status_error(resp).await) | ||
| 408 | - } | ||
| 409 | } | 390 | } |
| 410 | 391 | ||
| 411 | /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place. | 392 | /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place. |
| @@ -425,11 +406,7 @@ impl ForgeClient { | |||
| 425 | .timeout(REQUEST_TIMEOUT) | 406 | .timeout(REQUEST_TIMEOUT) |
| 426 | .send() | 407 | .send() |
| 427 | .await?; | 408 | .await?; |
| 428 | - if resp.status().is_success() { | 409 | + empty_or_error(resp).await |
| 429 | - Ok(()) | ||
| 430 | - } else { | ||
| 431 | - Err(status_error(resp).await) | ||
| 432 | - } | ||
| 433 | } | 410 | } |
| 434 | } | 411 | } |
| 435 | 412 | ||
| @@ -479,17 +456,10 @@ fn host_facts() -> HostFacts { | |||
| 479 | .and_then(|n| u32::try_from(n.get()).ok()); | 456 | .and_then(|n| u32::try_from(n.get()).ok()); |
| 480 | let memory_bytes = std::fs::read_to_string("/proc/meminfo") | 457 | let memory_bytes = std::fs::read_to_string("/proc/meminfo") |
| 481 | .ok() | 458 | .ok() |
| 482 | - .and_then(|text| parse_mem_total(&text)); | 459 | + .and_then(|text| crate::memory::meminfo(&text).total); |
| 483 | HostFacts { cpus, memory_bytes } | 460 | HostFacts { cpus, memory_bytes } |
| 484 | } | 461 | } |
| 485 | 462 | ||
| 486 | -/// `MemTotal` of `/proc/meminfo`, in bytes. The file reports kibibytes. | ||
| 487 | -fn parse_mem_total(meminfo: &str) -> Option<u64> { | ||
| 488 | - let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?; | ||
| 489 | - let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; | ||
| 490 | - kib.checked_mul(1024) | ||
| 491 | -} | ||
| 492 | - | ||
| 493 | async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T, ClientError> { | 463 | async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T, ClientError> { |
| 494 | if resp.status().is_success() { | 464 | if resp.status().is_success() { |
| 495 | Ok(resp.json().await?) | 465 | Ok(resp.json().await?) |
| @@ -498,6 +468,14 @@ async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T | |||
| 498 | } | 468 | } |
| 499 | } | 469 | } |
| 500 | 470 | ||
| 471 | +async fn empty_or_error(resp: reqwest::Response) -> Result<(), ClientError> { | ||
| 472 | + if resp.status().is_success() { | ||
| 473 | + Ok(()) | ||
| 474 | + } else { | ||
| 475 | + Err(status_error(resp).await) | ||
| 476 | + } | ||
| 477 | +} | ||
| 478 | + | ||
| 501 | async fn status_error(resp: reqwest::Response) -> ClientError { | 479 | async fn status_error(resp: reqwest::Response) -> ClientError { |
| 502 | let status = resp.status(); | 480 | let status = resp.status(); |
| 503 | let body = short_body(&resp.text().await.unwrap_or_default()); | 481 | let body = short_body(&resp.text().await.unwrap_or_default()); |
| @@ -524,13 +502,6 @@ fn short_body(text: &str) -> String { | |||
| 524 | mod tests { | 502 | mod tests { |
| 525 | use super::*; | 503 | use super::*; |
| 526 | 504 | ||
| 527 | - #[test] | ||
| 528 | - fn reads_mem_total_in_bytes() { | ||
| 529 | - let text = "MemTotal: 16384 kB\nMemFree: 100 kB\n"; | ||
| 530 | - assert_eq!(parse_mem_total(text), Some(16384 * 1024)); | ||
| 531 | - assert_eq!(parse_mem_total("nothing"), None); | ||
| 532 | - } | ||
| 533 | - | ||
| 534 | #[test] | 505 | #[test] |
| 535 | fn restart_header_must_name_a_mode() { | 506 | fn restart_header_must_name_a_mode() { |
| 536 | let mut headers = HeaderMap::new(); | 507 | let mut headers = HeaderMap::new(); |
crates/forge-runner/src/config.rsmodified+17 -54
| @@ -99,7 +99,6 @@ impl Limits { | |||
| 99 | let mut limits = self.clone(); | 99 | let mut limits = self.clone(); |
| 100 | let configured = forge_ci::size::parse_size(&self.memory); | 100 | let configured = forge_ci::size::parse_size(&self.memory); |
| 101 | match self.job_memory_limit(declared) { | 101 | match self.job_memory_limit(declared) { |
| 102 | - // The configured text stays as it is when it already is the limit. | ||
| 103 | Some(bytes) if declared.is_some() || Some(bytes) != configured => { | 102 | Some(bytes) if declared.is_some() || Some(bytes) != configured => { |
| 104 | limits.memory = bytes.to_string(); | 103 | limits.memory = bytes.to_string(); |
| 105 | } | 104 | } |
| @@ -311,9 +310,7 @@ impl RunnerConfig { | |||
| 311 | } | 310 | } |
| 312 | Ok(()) | 311 | Ok(()) |
| 313 | } | 312 | } |
| 314 | -} | ||
| 315 | 313 | ||
| 316 | -impl RunnerConfig { | ||
| 317 | /// The effective config as flat JSON by dotted key, for the forge's admin page. The runner | 314 | /// The effective config as flat JSON by dotted key, for the forge's admin page. The runner |
| 318 | /// secret and registry passwords are never included: the secret shows as `<redacted>` and a | 315 | /// secret and registry passwords are never included: the secret shows as `<redacted>` and a |
| 319 | /// registry shows only as `host (username)`. | 316 | /// registry shows only as `host (username)`. |
| @@ -354,18 +351,9 @@ impl RunnerConfig { | |||
| 354 | json!(self.limits.image_max_gb), | 351 | json!(self.limits.image_max_gb), |
| 355 | ); | 352 | ); |
| 356 | m.insert("limits.job_disk_gb".into(), json!(self.limits.job_disk_gb)); | 353 | m.insert("limits.job_disk_gb".into(), json!(self.limits.job_disk_gb)); |
| 357 | - let executor = match self.executor { | 354 | + m.insert("executor".into(), json!(self.executor)); |
| 358 | - ExecutorKind::Builtin => "builtin", | ||
| 359 | - ExecutorKind::Podman => "podman", | ||
| 360 | - }; | ||
| 361 | - m.insert("executor".into(), json!(executor)); | ||
| 362 | m.insert("images.keep_days".into(), json!(self.images.keep_days)); | 355 | m.insert("images.keep_days".into(), json!(self.images.keep_days)); |
| 363 | - let userns = match self.sandbox.userns { | 356 | + m.insert("sandbox.userns".into(), json!(self.sandbox.userns)); |
| 364 | - UsernsMode::Auto => "auto", | ||
| 365 | - UsernsMode::Single => "single", | ||
| 366 | - UsernsMode::Subuid => "subuid", | ||
| 367 | - }; | ||
| 368 | - m.insert("sandbox.userns".into(), json!(userns)); | ||
| 369 | m.insert("auto_update".into(), json!(self.auto_update)); | 357 | m.insert("auto_update".into(), json!(self.auto_update)); |
| 370 | m.insert("cache_max_gib".into(), json!(self.cache_max_gib)); | 358 | m.insert("cache_max_gib".into(), json!(self.cache_max_gib)); |
| 371 | let registries: Vec<String> = self | 359 | let registries: Vec<String> = self |
| @@ -444,32 +432,12 @@ impl RunnerConfig { | |||
| 444 | .map(|v| self.images.keep_days = v) | 432 | .map(|v| self.images.keep_days = v) |
| 445 | .is_some(), | 433 | .is_some(), |
| 446 | "cache_max_gib" => value.as_u64().map(|v| self.cache_max_gib = v).is_some(), | 434 | "cache_max_gib" => value.as_u64().map(|v| self.cache_max_gib = v).is_some(), |
| 447 | - "executor" => match value.as_str() { | 435 | + "executor" => ExecutorKind::deserialize(value) |
| 448 | - Some("builtin") => { | 436 | + .map(|v| self.executor = v) |
| 449 | - self.executor = ExecutorKind::Builtin; | 437 | + .is_ok(), |
| 450 | - true | 438 | + "sandbox.userns" => UsernsMode::deserialize(value) |
| 451 | - } | 439 | + .map(|v| self.sandbox.userns = v) |
| 452 | - Some("podman") => { | 440 | + .is_ok(), |
| 453 | - self.executor = ExecutorKind::Podman; | ||
| 454 | - true | ||
| 455 | - } | ||
| 456 | - _ => false, | ||
| 457 | - }, | ||
| 458 | - "sandbox.userns" => match value.as_str() { | ||
| 459 | - Some("auto") => { | ||
| 460 | - self.sandbox.userns = UsernsMode::Auto; | ||
| 461 | - true | ||
| 462 | - } | ||
| 463 | - Some("single") => { | ||
| 464 | - self.sandbox.userns = UsernsMode::Single; | ||
| 465 | - true | ||
| 466 | - } | ||
| 467 | - Some("subuid") => { | ||
| 468 | - self.sandbox.userns = UsernsMode::Subuid; | ||
| 469 | - true | ||
| 470 | - } | ||
| 471 | - _ => false, | ||
| 472 | - }, | ||
| 473 | _ => continue, | 441 | _ => continue, |
| 474 | }; | 442 | }; |
| 475 | if !ok { | 443 | if !ok { |
| @@ -495,16 +463,19 @@ impl RunnerConfig { | |||
| 495 | } | 463 | } |
| 496 | } | 464 | } |
| 497 | 465 | ||
| 466 | +fn home_join(rel: &str) -> Result<PathBuf, ConfigError> { | ||
| 467 | + let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?; | ||
| 468 | + Ok(PathBuf::from(home).join(rel)) | ||
| 469 | +} | ||
| 470 | + | ||
| 498 | /// The default config path: `$HOME/.config/forge-runner/runner.toml`. | 471 | /// The default config path: `$HOME/.config/forge-runner/runner.toml`. |
| 499 | pub fn default_config_path() -> Result<PathBuf, ConfigError> { | 472 | pub fn default_config_path() -> Result<PathBuf, ConfigError> { |
| 500 | - let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?; | 473 | + home_join(".config/forge-runner/runner.toml") |
| 501 | - Ok(PathBuf::from(home).join(".config/forge-runner/runner.toml")) | ||
| 502 | } | 474 | } |
| 503 | 475 | ||
| 504 | /// The default work directory: `$HOME/.cache/forge-runner/work`. | 476 | /// The default work directory: `$HOME/.cache/forge-runner/work`. |
| 505 | pub fn default_work_dir() -> Result<PathBuf, ConfigError> { | 477 | pub fn default_work_dir() -> Result<PathBuf, ConfigError> { |
| 506 | - let home = std::env::var_os("HOME").ok_or(ConfigError::NoHome)?; | 478 | + home_join(".cache/forge-runner/work") |
| 507 | - Ok(PathBuf::from(home).join(".cache/forge-runner/work")) | ||
| 508 | } | 479 | } |
| 509 | 480 | ||
| 510 | /// Reads and validates the config file. | 481 | /// Reads and validates the config file. |
| @@ -536,7 +507,6 @@ pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> { | |||
| 536 | .mode(0o600) | 507 | .mode(0o600) |
| 537 | .open(path) | 508 | .open(path) |
| 538 | .map_err(io_err)?; | 509 | .map_err(io_err)?; |
| 539 | - // `mode` only applies when the file is created; tighten a pre-existing file too. | ||
| 540 | file.set_permissions(std::fs::Permissions::from_mode(0o600)) | 510 | file.set_permissions(std::fs::Permissions::from_mode(0o600)) |
| 541 | .map_err(io_err)?; | 511 | .map_err(io_err)?; |
| 542 | file.write_all(text.as_bytes()).map_err(io_err)?; | 512 | file.write_all(text.as_bytes()).map_err(io_err)?; |
| @@ -546,6 +516,8 @@ pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> { | |||
| 546 | 516 | ||
| 547 | #[cfg(test)] | 517 | #[cfg(test)] |
| 548 | mod tests { | 518 | mod tests { |
| 519 | + use super::*; | ||
| 520 | + | ||
| 549 | #[test] | 521 | #[test] |
| 550 | fn report_redacts_secrets() { | 522 | fn report_redacts_secrets() { |
| 551 | let dir = tempfile::tempdir().expect("tempdir"); | 523 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -579,7 +551,6 @@ mod tests { | |||
| 579 | ); | 551 | ); |
| 580 | assert_eq!(lines.len(), 2, "{lines:?}"); | 552 | assert_eq!(lines.len(), 2, "{lines:?}"); |
| 581 | 553 | ||
| 582 | - // A value that breaks validation drops the whole set and keeps the config. | ||
| 583 | let before = config.clone(); | 554 | let before = config.clone(); |
| 584 | let mut bad = BTreeMap::new(); | 555 | let mut bad = BTreeMap::new(); |
| 585 | bad.insert("limits.image_max_gb".to_owned(), serde_json::json!(0)); | 556 | bad.insert("limits.image_max_gb".to_owned(), serde_json::json!(0)); |
| @@ -587,8 +558,6 @@ mod tests { | |||
| 587 | assert_eq!(config, before); | 558 | assert_eq!(config, before); |
| 588 | } | 559 | } |
| 589 | 560 | ||
| 590 | - use super::*; | ||
| 591 | - | ||
| 592 | fn sample(dir: &Path) -> RunnerConfig { | 561 | fn sample(dir: &Path) -> RunnerConfig { |
| 593 | RunnerConfig { | 562 | RunnerConfig { |
| 594 | url: "https://forge.example".to_owned(), | 563 | url: "https://forge.example".to_owned(), |
| @@ -685,15 +654,12 @@ mod tests { | |||
| 685 | fn cgroup_memory_is_the_declared_memory_plus_slack() { | 654 | fn cgroup_memory_is_the_declared_memory_plus_slack() { |
| 686 | let limits = Limits::default(); | 655 | let limits = Limits::default(); |
| 687 | let gib = 1u64 << 30; | 656 | let gib = 1u64 << 30; |
| 688 | - // Declared 4g: 4g plus 1/16, which is the 256 MiB minimum here. | ||
| 689 | assert_eq!( | 657 | assert_eq!( |
| 690 | limits.job_memory_limit(Some(4 * gib)), | 658 | limits.job_memory_limit(Some(4 * gib)), |
| 691 | Some(4 * gib + (256 << 20)) | 659 | Some(4 * gib + (256 << 20)) |
| 692 | ); | 660 | ); |
| 693 | - // Slack grows with big jobs and has a floor for small ones. | ||
| 694 | assert_eq!(memory_slack(32 * gib), 2 * gib); | 661 | assert_eq!(memory_slack(32 * gib), 2 * gib); |
| 695 | assert_eq!(memory_slack(512 << 20), 256 << 20); | 662 | assert_eq!(memory_slack(512 << 20), 256 << 20); |
| 696 | - // The declared value wins over limits.memory, in both directions. | ||
| 697 | let small = Limits { | 663 | let small = Limits { |
| 698 | memory: "8g".into(), | 664 | memory: "8g".into(), |
| 699 | ..Limits::default() | 665 | ..Limits::default() |
| @@ -710,7 +676,6 @@ mod tests { | |||
| 710 | let gib = 1u64 << 30; | 676 | let gib = 1u64 << 30; |
| 711 | let limits = Limits::default(); | 677 | let limits = Limits::default(); |
| 712 | assert_eq!(limits.job_memory_limit(None), Some(4 * gib)); | 678 | assert_eq!(limits.job_memory_limit(None), Some(4 * gib)); |
| 713 | - // The configured text is kept as it is. | ||
| 714 | assert_eq!(limits.for_job(None).memory, "4g"); | 679 | assert_eq!(limits.for_job(None).memory, "4g"); |
| 715 | let big_reserve = Limits { | 680 | let big_reserve = Limits { |
| 716 | reserve_memory: "6g".into(), | 681 | reserve_memory: "6g".into(), |
| @@ -724,7 +689,6 @@ mod tests { | |||
| 724 | }; | 689 | }; |
| 725 | assert_eq!(bad.job_memory_limit(None), None); | 690 | assert_eq!(bad.job_memory_limit(None), None); |
| 726 | assert_eq!(bad.for_job(None).memory, "lots"); | 691 | assert_eq!(bad.for_job(None).memory, "lots"); |
| 727 | - // Builtin: no `memory` means the whole budget; a declared one keeps its slack. | ||
| 728 | assert_eq!( | 692 | assert_eq!( |
| 729 | limits.for_builtin_job(None, Some(6 * gib), 0).memory, | 693 | limits.for_builtin_job(None, Some(6 * gib), 0).memory, |
| 730 | (6 * gib).to_string() | 694 | (6 * gib).to_string() |
| @@ -796,7 +760,6 @@ mod tests { | |||
| 796 | assert_eq!(config.registries.len(), 1); | 760 | assert_eq!(config.registries.len(), 1); |
| 797 | assert_eq!(config.registries[0].host, "ghcr.io"); | 761 | assert_eq!(config.registries[0].host, "ghcr.io"); |
| 798 | 762 | ||
| 799 | - // A save keeps the image cap and the registry, and the file still loads. | ||
| 800 | save(&path, &config).expect("save"); | 763 | save(&path, &config).expect("save"); |
| 801 | assert_eq!(load(&path).expect("reload"), config); | 764 | assert_eq!(load(&path).expect("reload"), config); |
| 802 | } | 765 | } |
crates/forge-runner/src/executor.rsmodified+0 -104
| @@ -1,16 +1,3 @@ | |||
| 1 | -//! Running a job's `run` script. | ||
| 2 | -//! | ||
| 3 | -//! `BuiltinExecutor` is the default: the image is prepared by an [`ImageSource`] (the | ||
| 4 | -//! [`ImageStore`] in production), and the script runs in a sandbox started by a helper process | ||
| 5 | -//! (`forge-runner __sandbox`). No external tool is needed. | ||
| 6 | -//! | ||
| 7 | -//! `PodmanExecutor` is the optional path: a rootless podman container with the workspace | ||
| 8 | -//! mounted at `/workspace`. Secret values and job env travel in the child process environment, | ||
| 9 | -//! and podman receives only `-e NAME`, so no value ever appears in argv. | ||
| 10 | -//! | ||
| 11 | -//! `HostExecutor` runs the script directly on the host. It exists only for tests and is compiled | ||
| 12 | -//! only under `cfg(test)` or the `test-host-executor` feature. | ||
| 13 | - | ||
| 14 | use std::fs; | 1 | use std::fs; |
| 15 | use std::future::Future; | 2 | use std::future::Future; |
| 16 | use std::path::{Path, PathBuf}; | 3 | use std::path::{Path, PathBuf}; |
| @@ -39,34 +26,21 @@ use crate::sandbox::idmap::{IdMap, remove_tree}; | |||
| 39 | use crate::sandbox::{SandboxRequest, job_cgroup_path}; | 26 | use crate::sandbox::{SandboxRequest, job_cgroup_path}; |
| 40 | use crate::workspace::validate_job_id; | 27 | use crate::workspace::validate_job_id; |
| 41 | 28 | ||
| 42 | -/// The prefix of the sandbox helper's own error lines on stderr. | ||
| 43 | const SANDBOX_PREFIX: &[u8] = b"forge-sandbox: "; | 29 | const SANDBOX_PREFIX: &[u8] = b"forge-sandbox: "; |
| 44 | 30 | ||
| 45 | -/// How long to wait for the output readers to drain after the child has exited. | ||
| 46 | const READER_GRACE: Duration = Duration::from_secs(10); | 31 | const READER_GRACE: Duration = Duration::from_secs(10); |
| 47 | -/// How long to wait for the child to exit after it has been told to stop. | ||
| 48 | const STOP_GRACE: Duration = Duration::from_secs(30); | 32 | const STOP_GRACE: Duration = Duration::from_secs(30); |
| 49 | 33 | ||
| 50 | -/// Everything an executor needs to run one job. | ||
| 51 | pub struct ExecRequest<'a> { | 34 | pub struct ExecRequest<'a> { |
| 52 | pub job: &'a JobAssignment, | 35 | pub job: &'a JobAssignment, |
| 53 | - /// The checked-out source tree. The script runs with it as `/workspace` or as its cwd. | ||
| 54 | pub workspace: &'a Path, | 36 | pub workspace: &'a Path, |
| 55 | - /// Where merged stdout and stderr go, one line per message. | ||
| 56 | pub logs: mpsc::Sender<Vec<u8>>, | 37 | pub logs: mpsc::Sender<Vec<u8>>, |
| 57 | - /// Cancelling this stops the job. The executor then reports `Outcome::Cancelled`. | ||
| 58 | pub cancel: CancellationToken, | 38 | pub cancel: CancellationToken, |
| 59 | - /// Where the executor leaves OOM kills it saw in the job's cgroup. Executors that cannot see | ||
| 60 | - /// them leave it alone. | ||
| 61 | pub oom: OomSink, | 39 | pub oom: OomSink, |
| 62 | - /// The RAM part of the runner's memory budget now. The builtin executor gives a job without | ||
| 63 | - /// `memory` this as its cgroup limit; `None` keeps the configured `limits.memory`. | ||
| 64 | pub memory_budget: Option<u64>, | 40 | pub memory_budget: Option<u64>, |
| 65 | - /// The swap part of the budget, which a job without `memory` may use on top of it. | ||
| 66 | pub memory_swap: u64, | 41 | pub memory_swap: u64, |
| 67 | } | 42 | } |
| 68 | 43 | ||
| 69 | -/// The executor's answer. The runner adds timeouts and artifact results on top of it. | ||
| 70 | #[derive(Clone, Debug, PartialEq, Eq)] | 44 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 71 | pub struct ExecResult { | 45 | pub struct ExecResult { |
| 72 | pub outcome: Outcome, | 46 | pub outcome: Outcome, |
| @@ -74,23 +48,18 @@ pub struct ExecResult { | |||
| 74 | pub message: Option<String>, | 48 | pub message: Option<String>, |
| 75 | } | 49 | } |
| 76 | 50 | ||
| 77 | -/// The boxed future an executor returns. Written out so `Executor` stays object safe. | ||
| 78 | pub type ExecFuture<'a> = Pin<Box<dyn Future<Output = ExecResult> + Send + 'a>>; | 51 | pub type ExecFuture<'a> = Pin<Box<dyn Future<Output = ExecResult> + Send + 'a>>; |
| 79 | 52 | ||
| 80 | -/// Runs jobs. The runner holds one as `Arc<dyn Executor>`. | ||
| 81 | pub trait Executor: Send + Sync { | 53 | pub trait Executor: Send + Sync { |
| 82 | fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a>; | 54 | fn run<'a>(&'a self, req: ExecRequest<'a>) -> ExecFuture<'a>; |
| 83 | } | 55 | } |
| 84 | 56 | ||
| 85 | -/// An executor failure, reported as `Outcome::Error`. | ||
| 86 | #[derive(Debug, thiserror::Error)] | 57 | #[derive(Debug, thiserror::Error)] |
| 87 | pub enum ExecError { | 58 | pub enum ExecError { |
| 88 | #[error("invalid job: {0}")] | 59 | #[error("invalid job: {0}")] |
| 89 | Invalid(String), | 60 | Invalid(String), |
| 90 | } | 61 | } |
| 91 | 62 | ||
| 92 | -/// Env names go to podman as `-e NAME`, so they must be plain identifiers. A name with `=` in it | ||
| 93 | -/// would carry a value into argv. | ||
| 94 | pub fn validate_env_name(name: &str) -> Result<(), ExecError> { | 63 | pub fn validate_env_name(name: &str) -> Result<(), ExecError> { |
| 95 | let mut chars = name.chars(); | 64 | let mut chars = name.chars(); |
| 96 | let first_ok = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_'); | 65 | let first_ok = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_'); |
| @@ -102,7 +71,6 @@ pub fn validate_env_name(name: &str) -> Result<(), ExecError> { | |||
| 102 | } | 71 | } |
| 103 | } | 72 | } |
| 104 | 73 | ||
| 105 | -/// The job's env and secrets as name/value pairs. Secrets win over plain env on a clash. | ||
| 106 | pub fn job_env(job: &JobAssignment) -> Result<Vec<(String, String)>, ExecError> { | 74 | pub fn job_env(job: &JobAssignment) -> Result<Vec<(String, String)>, ExecError> { |
| 107 | let mut pairs: Vec<(String, String)> = Vec::new(); | 75 | let mut pairs: Vec<(String, String)> = Vec::new(); |
| 108 | for (k, v) in job.env.iter().chain(job.secrets.iter()) { | 76 | for (k, v) in job.env.iter().chain(job.secrets.iter()) { |
| @@ -113,8 +81,6 @@ pub fn job_env(job: &JobAssignment) -> Result<Vec<(String, String)>, ExecError> | |||
| 113 | Ok(pairs) | 81 | Ok(pairs) |
| 114 | } | 82 | } |
| 115 | 83 | ||
| 116 | -/// How many things a job should build at once: its CPU limit rounded up, at least 1 and at most | ||
| 117 | -/// the host's CPUs. The runner decides this, not the workflow, since only it knows the machine. | ||
| 118 | pub fn job_parallelism(limits: &Limits) -> u32 { | 84 | pub fn job_parallelism(limits: &Limits) -> u32 { |
| 119 | let host = std::thread::available_parallelism().map_or(1, |n| n.get() as u32); | 85 | let host = std::thread::available_parallelism().map_or(1, |n| n.get() as u32); |
| 120 | let cpus = limits | 86 | let cpus = limits |
| @@ -127,9 +93,6 @@ pub fn job_parallelism(limits: &Limits) -> u32 { | |||
| 127 | cpus.clamp(1, host.max(1)) | 93 | cpus.clamp(1, host.max(1)) |
| 128 | } | 94 | } |
| 129 | 95 | ||
| 130 | -/// The job's env with the runner's defaults under it: `FORGE_CPUS`, `FORGE_MEMORY_BYTES` (the job's | ||
| 131 | -/// memory limit) and the parallelism knobs common build tools read (cargo, make, cmake). A job that | ||
| 132 | -/// sets one of them itself keeps its own value. | ||
| 133 | pub fn job_env_with_defaults( | 96 | pub fn job_env_with_defaults( |
| 134 | job: &JobAssignment, | 97 | job: &JobAssignment, |
| 135 | limits: &Limits, | 98 | limits: &Limits, |
| @@ -156,7 +119,6 @@ pub fn job_env_with_defaults( | |||
| 156 | Ok(pairs) | 119 | Ok(pairs) |
| 157 | } | 120 | } |
| 158 | 121 | ||
| 159 | -/// The podman invocation for a job: argv (no values in it) and the env the child needs. | ||
| 160 | #[derive(Debug, PartialEq, Eq)] | 122 | #[derive(Debug, PartialEq, Eq)] |
| 161 | pub struct PodmanInvocation { | 123 | pub struct PodmanInvocation { |
| 162 | pub args: Vec<String>, | 124 | pub args: Vec<String>, |
| @@ -165,7 +127,6 @@ pub struct PodmanInvocation { | |||
| 165 | } | 127 | } |
| 166 | 128 | ||
| 167 | fn check_image(image: &str) -> Result<(), ExecError> { | 129 | fn check_image(image: &str) -> Result<(), ExecError> { |
| 168 | - // Podman would read a leading `-` as an option, and whitespace is never valid in a reference. | ||
| 169 | if image.is_empty() || image.starts_with('-') || image.contains(char::is_whitespace) { | 130 | if image.is_empty() || image.starts_with('-') || image.contains(char::is_whitespace) { |
| 170 | return Err(ExecError::Invalid(format!("bad image {image:?}"))); | 131 | return Err(ExecError::Invalid(format!("bad image {image:?}"))); |
| 171 | } | 132 | } |
| @@ -183,7 +144,6 @@ fn check_limit(value: &str, what: &str) -> Result<(), ExecError> { | |||
| 183 | } | 144 | } |
| 184 | } | 145 | } |
| 185 | 146 | ||
| 186 | -/// Builds the podman invocation for `job`. Pure, so the argv can be tested. | ||
| 187 | pub fn podman_invocation( | 147 | pub fn podman_invocation( |
| 188 | job: &JobAssignment, | 148 | job: &JobAssignment, |
| 189 | workspace: &Path, | 149 | workspace: &Path, |
| @@ -252,7 +212,6 @@ pub fn podman_invocation( | |||
| 252 | }) | 212 | }) |
| 253 | } | 213 | } |
| 254 | 214 | ||
| 255 | -/// How a finished child maps to a job result. | ||
| 256 | fn classify(status: ExitStatus) -> ExecResult { | 215 | fn classify(status: ExitStatus) -> ExecResult { |
| 257 | match status.code() { | 216 | match status.code() { |
| 258 | Some(0) => ExecResult { | 217 | Some(0) => ExecResult { |
| @@ -260,7 +219,6 @@ fn classify(status: ExitStatus) -> ExecResult { | |||
| 260 | exit_code: Some(0), | 219 | exit_code: Some(0), |
| 261 | message: None, | 220 | message: None, |
| 262 | }, | 221 | }, |
| 263 | - // podman itself exits 125 when it cannot run the container (no image, no storage, ...). | ||
| 264 | Some(125) => ExecResult { | 222 | Some(125) => ExecResult { |
| 265 | outcome: Outcome::Error, | 223 | outcome: Outcome::Error, |
| 266 | exit_code: Some(125), | 224 | exit_code: Some(125), |
| @@ -287,7 +245,6 @@ fn error_result(message: impl Into<String>) -> ExecResult { | |||
| 287 | } | 245 | } |
| 288 | } | 246 | } |
| 289 | 247 | ||
| 290 | -/// How to stop a job when it is cancelled. | ||
| 291 | enum Stopper { | 248 | enum Stopper { |
| 292 | Podman { | 249 | Podman { |
| 293 | container: String, | 250 | container: String, |
| @@ -296,7 +253,6 @@ enum Stopper { | |||
| 296 | ProcessGroup { | 253 | ProcessGroup { |
| 297 | pid: u32, | 254 | pid: u32, |
| 298 | }, | 255 | }, |
| 299 | - /// The sandbox helper. It is sent SIGTERM and stops its own container, see [`stop_child`]. | ||
| 300 | Helper { | 256 | Helper { |
| 301 | pid: u32, | 257 | pid: u32, |
| 302 | }, | 258 | }, |
| @@ -334,10 +290,6 @@ impl Stopper { | |||
| 334 | } | 290 | } |
| 335 | } | 291 | } |
| 336 | 292 | ||
| 337 | -/// Stops the child on cancellation and returns its exit status. | ||
| 338 | -/// | ||
| 339 | -/// The sandbox helper gets SIGTERM and gets to kill and delete its container itself. SIGKILL | ||
| 340 | -/// follows only if it does not exit within [`STOP_GRACE`]. Other children are killed at once. | ||
| 341 | async fn stop_child(child: &mut Child, stopper: Stopper) -> std::io::Result<ExitStatus> { | 293 | async fn stop_child(child: &mut Child, stopper: Stopper) -> std::io::Result<ExitStatus> { |
| 342 | if let Stopper::Helper { pid } = stopper { | 294 | if let Stopper::Helper { pid } = stopper { |
| 343 | let _ = kill(Pid::from_raw(pid as i32), Signal::SIGTERM); | 295 | let _ = kill(Pid::from_raw(pid as i32), Signal::SIGTERM); |
| @@ -356,17 +308,13 @@ async fn stop_child(child: &mut Child, stopper: Stopper) -> std::io::Result<Exit | |||
| 356 | .unwrap_or_else(|_| Err(std::io::Error::other("child did not stop"))) | 308 | .unwrap_or_else(|_| Err(std::io::Error::other("child did not stop"))) |
| 357 | } | 309 | } |
| 358 | 310 | ||
| 359 | -/// What [`supervise`] saw when the child finished. | ||
| 360 | struct Supervised { | 311 | struct Supervised { |
| 361 | cancelled: bool, | 312 | cancelled: bool, |
| 362 | status: std::io::Result<ExitStatus>, | 313 | status: std::io::Result<ExitStatus>, |
| 363 | - /// The sandbox helper's last `forge-sandbox: <reason>` line on stderr, when it printed one. | ||
| 364 | sandbox_error: Option<String>, | 314 | sandbox_error: Option<String>, |
| 365 | - /// The OOM counters the helper printed, when something in the job was OOM-killed. | ||
| 366 | oom: Option<OomEvents>, | 315 | oom: Option<OomEvents>, |
| 367 | } | 316 | } |
| 368 | 317 | ||
| 369 | -/// Copies stderr lines to the log and remembers the last sandbox error line. | ||
| 370 | async fn tap_sandbox_errors( | 318 | async fn tap_sandbox_errors( |
| 371 | mut lines: mpsc::Receiver<Vec<u8>>, | 319 | mut lines: mpsc::Receiver<Vec<u8>>, |
| 372 | logs: mpsc::Sender<Vec<u8>>, | 320 | logs: mpsc::Sender<Vec<u8>>, |
| @@ -374,7 +322,6 @@ async fn tap_sandbox_errors( | |||
| 374 | let mut found = None; | 322 | let mut found = None; |
| 375 | let mut oom = None; | 323 | let mut oom = None; |
| 376 | while let Some(chunk) = lines.recv().await { | 324 | while let Some(chunk) = lines.recv().await { |
| 377 | - // The OOM line is for the runner, not for the job log. | ||
| 378 | if chunk.starts_with(SANDBOX_PREFIX) | 325 | if chunk.starts_with(SANDBOX_PREFIX) |
| 379 | && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk)) | 326 | && let Some(events) = OomEvents::from_line(&String::from_utf8_lossy(&chunk)) |
| 380 | { | 327 | { |
| @@ -393,9 +340,6 @@ async fn tap_sandbox_errors( | |||
| 393 | (found, oom) | 340 | (found, oom) |
| 394 | } | 341 | } |
| 395 | 342 | ||
| 396 | -/// Forwards the child's output, waits for it, and reports how it ended. On cancellation the | ||
| 397 | -/// child is stopped first. `cleanup` runs as soon as the child has exited, before the output is | ||
| 398 | -/// drained: a container keeps the output pipes open until it is killed. | ||
| 399 | async fn supervise( | 343 | async fn supervise( |
| 400 | mut child: Child, | 344 | mut child: Child, |
| 401 | logs: mpsc::Sender<Vec<u8>>, | 345 | logs: mpsc::Sender<Vec<u8>>, |
| @@ -415,7 +359,6 @@ async fn supervise( | |||
| 415 | } | 359 | } |
| 416 | drop(logs); | 360 | drop(logs); |
| 417 | 361 | ||
| 418 | - // The wait future must be dropped before the stop path borrows the child again. | ||
| 419 | let early = tokio::select! { | 362 | let early = tokio::select! { |
| 420 | status = child.wait() => Some(status), | 363 | status = child.wait() => Some(status), |
| 421 | _ = cancel.cancelled() => None, | 364 | _ = cancel.cancelled() => None, |
| @@ -434,7 +377,6 @@ async fn supervise( | |||
| 434 | } | 377 | } |
| 435 | }; | 378 | }; |
| 436 | if tokio::time::timeout(READER_GRACE, drain).await.is_err() { | 379 | if tokio::time::timeout(READER_GRACE, drain).await.is_err() { |
| 437 | - // A grandchild still holds the pipe. Stop reading rather than hang the job. | ||
| 438 | for reader in &readers { | 380 | for reader in &readers { |
| 439 | reader.abort(); | 381 | reader.abort(); |
| 440 | } | 382 | } |
| @@ -455,7 +397,6 @@ async fn supervise( | |||
| 455 | } | 397 | } |
| 456 | } | 398 | } |
| 457 | 399 | ||
| 458 | -/// The result for a child that was supervised with the podman or host rules. | ||
| 459 | fn finish(supervised: Supervised) -> ExecResult { | 400 | fn finish(supervised: Supervised) -> ExecResult { |
| 460 | if supervised.cancelled { | 401 | if supervised.cancelled { |
| 461 | return cancelled_result(); | 402 | return cancelled_result(); |
| @@ -474,7 +415,6 @@ fn cancelled_result() -> ExecResult { | |||
| 474 | } | 415 | } |
| 475 | } | 416 | } |
| 476 | 417 | ||
| 477 | -/// Runs jobs in rootless podman. | ||
| 478 | #[derive(Clone, Debug)] | 418 | #[derive(Clone, Debug)] |
| 479 | pub struct PodmanExecutor { | 419 | pub struct PodmanExecutor { |
| 480 | limits: Limits, | 420 | limits: Limits, |
| @@ -520,7 +460,6 @@ impl Executor for PodmanExecutor { | |||
| 520 | } | 460 | } |
| 521 | } | 461 | } |
| 522 | 462 | ||
| 523 | -/// Runs the script on the host with no isolation. Tests only. | ||
| 524 | #[cfg(any(test, feature = "test-host-executor"))] | 463 | #[cfg(any(test, feature = "test-host-executor"))] |
| 525 | #[derive(Clone, Copy, Debug, Default)] | 464 | #[derive(Clone, Copy, Debug, Default)] |
| 526 | pub struct HostExecutor; | 465 | pub struct HostExecutor; |
| @@ -563,10 +502,7 @@ impl Executor for HostExecutor { | |||
| 563 | } | 502 | } |
| 564 | } | 503 | } |
| 565 | 504 | ||
| 566 | -/// Where the builtin executor gets its rootfs. [`ImageStore`] pulls and unpacks images. Tests | ||
| 567 | -/// supply a local rootfs directory instead. | ||
| 568 | pub trait ImageSource: Send + Sync { | 505 | pub trait ImageSource: Send + Sync { |
| 569 | - /// Makes `image` available and returns its rootfs and config. Progress lines go to `log`. | ||
| 570 | fn prepare<'a>( | 506 | fn prepare<'a>( |
| 571 | &'a self, | 507 | &'a self, |
| 572 | image: &'a str, | 508 | image: &'a str, |
| @@ -586,17 +522,12 @@ impl ImageSource for ImageStore { | |||
| 586 | } | 522 | } |
| 587 | } | 523 | } |
| 588 | 524 | ||
| 589 | -/// Runs jobs in a libcontainer sandbox, started as `helper` (`forge-runner __sandbox`). It needs | ||
| 590 | -/// no external container tool. See `docs/ci.md`. | ||
| 591 | pub struct BuiltinExecutor<I = ImageStore> { | 525 | pub struct BuiltinExecutor<I = ImageStore> { |
| 592 | images: I, | 526 | images: I, |
| 593 | limits: Limits, | 527 | limits: Limits, |
| 594 | helper: PathBuf, | 528 | helper: PathBuf, |
| 595 | - /// Holds one `<job id>` directory per running job, for the overlay and container state. | ||
| 596 | jobs_dir: PathBuf, | 529 | jobs_dir: PathBuf, |
| 597 | - /// `[[registry]]` logins, as (host, login). | ||
| 598 | registries: Vec<(String, RegistryAuth)>, | 530 | registries: Vec<(String, RegistryAuth)>, |
| 599 | - /// The id map jobs run under. Single unless set by [`BuiltinExecutor::with_idmap`]. | ||
| 600 | idmap: IdMap, | 531 | idmap: IdMap, |
| 601 | } | 532 | } |
| 602 | 533 | ||
| @@ -612,13 +543,11 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 612 | } | 543 | } |
| 613 | } | 544 | } |
| 614 | 545 | ||
| 615 | - /// Sets the id map that jobs run under. Job dirs are removed under it too. | ||
| 616 | pub fn with_idmap(mut self, map: IdMap) -> Self { | 546 | pub fn with_idmap(mut self, map: IdMap) -> Self { |
| 617 | self.idmap = map; | 547 | self.idmap = map; |
| 618 | self | 548 | self |
| 619 | } | 549 | } |
| 620 | 550 | ||
| 621 | - /// Sets the `[[registry]]` logins. Each one is used for images on its host. | ||
| 622 | pub fn with_registries(mut self, registries: &[RegistryConfig]) -> Self { | 551 | pub fn with_registries(mut self, registries: &[RegistryConfig]) -> Self { |
| 623 | self.registries = registries | 552 | self.registries = registries |
| 624 | .iter() | 553 | .iter() |
| @@ -635,7 +564,6 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 635 | self | 564 | self |
| 636 | } | 565 | } |
| 637 | 566 | ||
| 638 | - /// The login for `image`, matched by its registry host. Docker Hub is `docker.io`. | ||
| 639 | fn auth_for(&self, image: &str) -> Option<&RegistryAuth> { | 567 | fn auth_for(&self, image: &str) -> Option<&RegistryAuth> { |
| 640 | let reference: Reference = image.parse().ok()?; | 568 | let reference: Reference = image.parse().ok()?; |
| 641 | let host = reference.registry(); | 569 | let host = reference.registry(); |
| @@ -684,8 +612,6 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 684 | .await; | 612 | .await; |
| 685 | 613 | ||
| 686 | let job_dir = self.jobs_dir.join(&job.job_id); | 614 | let job_dir = self.jobs_dir.join(&job.job_id); |
| 687 | - // A leftover from an earlier run of this job id would hold stale overlay state, and maybe | ||
| 688 | - // the pid of a pasta that outlived its helper. | ||
| 689 | crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); | 615 | crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job_dir)); |
| 690 | if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await { | 616 | if let Err(e) = remove_job_dir(&self.idmap, &self.helper, &job_dir).await { |
| 691 | tracing::warn!("cannot remove stale {}: {e}", job_dir.display()); | 617 | tracing::warn!("cannot remove stale {}: {e}", job_dir.display()); |
| @@ -718,7 +644,6 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 718 | limits, | 644 | limits, |
| 719 | idmap: self.idmap.clone(), | 645 | idmap: self.idmap.clone(), |
| 720 | }; | 646 | }; |
| 721 | - // The request holds the secrets. It goes to the helper's stdin and nowhere else. | ||
| 722 | let json = match serde_json::to_vec(&request) { | 647 | let json = match serde_json::to_vec(&request) { |
| 723 | Ok(json) => json, | 648 | Ok(json) => json, |
| 724 | Err(e) => return error_result(format!("cannot encode the sandbox request: {e}")), | 649 | Err(e) => return error_result(format!("cannot encode the sandbox request: {e}")), |
| @@ -739,15 +664,12 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 739 | return error_result("sandbox helper exited before its pid was read"); | 664 | return error_result("sandbox helper exited before its pid was read"); |
| 740 | }; | 665 | }; |
| 741 | if let Some(mut stdin) = child.stdin.take() { | 666 | if let Some(mut stdin) = child.stdin.take() { |
| 742 | - // The helper reads the whole request before it does anything else. | ||
| 743 | if let Err(e) = stdin.write_all(&json).await { | 667 | if let Err(e) = stdin.write_all(&json).await { |
| 744 | return error_result(format!("cannot send the job to the sandbox helper: {e}")); | 668 | return error_result(format!("cannot send the job to the sandbox helper: {e}")); |
| 745 | } | 669 | } |
| 746 | } | 670 | } |
| 747 | drop(json); | 671 | drop(json); |
| 748 | 672 | ||
| 749 | - // The disk cap stops the job through its own token, so a stop for disk can be told apart | ||
| 750 | - // from a cancel. | ||
| 751 | let job_cancel = cancel.child_token(); | 673 | let job_cancel = cancel.child_token(); |
| 752 | let over_disk = Arc::new(AtomicBool::new(false)); | 674 | let over_disk = Arc::new(AtomicBool::new(false)); |
| 753 | let disk_cap = disk_gb.saturating_mul(1 << 30); | 675 | let disk_cap = disk_gb.saturating_mul(1 << 30); |
| @@ -811,7 +733,6 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 811 | exit_code: Some(0), | 733 | exit_code: Some(0), |
| 812 | message: None, | 734 | message: None, |
| 813 | }, | 735 | }, |
| 814 | - // The helper's own setup failure. A job that exits 125 by itself is a failure. | ||
| 815 | Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => { | 736 | Some(EXIT_SETUP_FAILED) if sandbox_error.is_some() => { |
| 816 | let line = sandbox_error.unwrap_or_default(); | 737 | let line = sandbox_error.unwrap_or_default(); |
| 817 | let reason = line.strip_prefix("forge-sandbox: ").unwrap_or(&line); | 738 | let reason = line.strip_prefix("forge-sandbox: ").unwrap_or(&line); |
| @@ -836,14 +757,10 @@ impl<I: ImageSource> BuiltinExecutor<I> { | |||
| 836 | } | 757 | } |
| 837 | } | 758 | } |
| 838 | 759 | ||
| 839 | -/// Where cgroup2 is mounted. Job cgroup paths are relative to it. | ||
| 840 | const CGROUP_ROOT: &str = "/sys/fs/cgroup"; | 760 | const CGROUP_ROOT: &str = "/sys/fs/cgroup"; |
| 841 | -/// How often, and how many times, to retry removing a job cgroup while its processes exit. | ||
| 842 | const REAP_POLL: Duration = Duration::from_millis(100); | 761 | const REAP_POLL: Duration = Duration::from_millis(100); |
| 843 | const REAP_POLLS: u32 = 50; | 762 | const REAP_POLLS: u32 = 50; |
| 844 | 763 | ||
| 845 | -/// Kills every process in a job cgroup. `cgroup.kill` does it in one write (Linux 5.14 and up). | ||
| 846 | -/// Older kernels get a SIGKILL to each pid in `cgroup.procs`. | ||
| 847 | pub(crate) fn kill_cgroup(dir: &Path) { | 764 | pub(crate) fn kill_cgroup(dir: &Path) { |
| 848 | if fs::write(dir.join("cgroup.kill"), "1").is_ok() { | 765 | if fs::write(dir.join("cgroup.kill"), "1").is_ok() { |
| 849 | return; | 766 | return; |
| @@ -859,7 +776,6 @@ pub(crate) fn kill_cgroup(dir: &Path) { | |||
| 859 | } | 776 | } |
| 860 | } | 777 | } |
| 861 | 778 | ||
| 862 | -/// What to clean up once a job's sandbox helper has exited. See [`reap_job`]. | ||
| 863 | struct JobCleanup { | 779 | struct JobCleanup { |
| 864 | helper_pid: u32, | 780 | helper_pid: u32, |
| 865 | job_id: String, | 781 | job_id: String, |
| @@ -868,15 +784,11 @@ struct JobCleanup { | |||
| 868 | helper: PathBuf, | 784 | helper: PathBuf, |
| 869 | } | 785 | } |
| 870 | 786 | ||
| 871 | -/// Cleans up after a job's helper has exited, whatever the reason. A helper killed with SIGKILL | ||
| 872 | -/// cannot delete its container, so the container could otherwise keep running. This kills what is | ||
| 873 | -/// left in the job cgroup, removes the cgroup, stops a leftover pasta, and removes the job dir. | ||
| 874 | async fn reap_job(job: &JobCleanup) { | 787 | async fn reap_job(job: &JobCleanup) { |
| 875 | if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) { | 788 | if let Ok(relative) = job_cgroup_path(&job.job_id, job.helper_pid) { |
| 876 | let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative)); | 789 | let dir = Path::new(CGROUP_ROOT).join(relative.strip_prefix("/").unwrap_or(&relative)); |
| 877 | if dir.exists() { | 790 | if dir.exists() { |
| 878 | kill_cgroup(&dir); | 791 | kill_cgroup(&dir); |
| 879 | - // rmdir fails while processes remain, so retry until they have exited. | ||
| 880 | for _ in 0..REAP_POLLS { | 792 | for _ in 0..REAP_POLLS { |
| 881 | if fs::remove_dir(&dir).is_ok() || !dir.exists() { | 793 | if fs::remove_dir(&dir).is_ok() || !dir.exists() { |
| 882 | break; | 794 | break; |
| @@ -885,18 +797,12 @@ async fn reap_job(job: &JobCleanup) { | |||
| 885 | } | 797 | } |
| 886 | } | 798 | } |
| 887 | } | 799 | } |
| 888 | - // A helper killed with SIGKILL could not stop its pasta either. | ||
| 889 | crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job.job_dir)); | 800 | crate::sandbox::net::stop_pasta(&crate::sandbox::net::pid_file(&job.job_dir)); |
| 890 | if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await { | 801 | if let Err(e) = remove_job_dir(&job.idmap, &job.helper, &job.job_dir).await { |
| 891 | tracing::warn!("cannot remove {}: {e}", job.job_dir.display()); | 802 | tracing::warn!("cannot remove {}: {e}", job.job_dir.display()); |
| 892 | } | 803 | } |
| 893 | } | 804 | } |
| 894 | 805 | ||
| 895 | -/// Cleans up after an earlier run of the runner that did not get to (a crash, a SIGKILL, a power | ||
| 896 | -/// cut): for every leftover `work_dir/jobs/<id>` it stops a pasta, kills the job's cgroups and | ||
| 897 | -/// removes the dir, and it removes leftover workspaces `work_dir/<id>`. Call it at startup, | ||
| 898 | -/// before any job runs. Only job ids found in this runner's own dirs are touched, so another | ||
| 899 | -/// runner's jobs in a shared cgroup are left alone. | ||
| 900 | pub async fn sweep_leftovers(work_dir: &Path, map: &IdMap, helper: &Path) { | 806 | pub async fn sweep_leftovers(work_dir: &Path, map: &IdMap, helper: &Path) { |
| 901 | let (work_dir, map, helper) = (work_dir.to_owned(), map.clone(), helper.to_owned()); | 807 | let (work_dir, map, helper) = (work_dir.to_owned(), map.clone(), helper.to_owned()); |
| 902 | let swept = tokio::task::spawn_blocking(move || sweep_blocking(&work_dir, &map, &helper)).await; | 808 | let swept = tokio::task::spawn_blocking(move || sweep_blocking(&work_dir, &map, &helper)).await; |
| @@ -944,8 +850,6 @@ fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) { | |||
| 944 | tracing::warn!("cannot remove {}: {e}", job_dir.display()); | 850 | tracing::warn!("cannot remove {}: {e}", job_dir.display()); |
| 945 | } | 851 | } |
| 946 | } | 852 | } |
| 947 | - // `work_dir` may be shared with other files (an operator could point it at a home dir), so | ||
| 948 | - // only names shaped like the forge's job ids (ULIDs) count as workspaces. | ||
| 949 | for job_id in job_ids_in(work_dir).into_iter().filter(|id| is_ulid(id)) { | 853 | for job_id in job_ids_in(work_dir).into_iter().filter(|id| is_ulid(id)) { |
| 950 | let workspace = work_dir.join(&job_id); | 854 | let workspace = work_dir.join(&job_id); |
| 951 | tracing::info!("removing leftover workspace {job_id}"); | 855 | tracing::info!("removing leftover workspace {job_id}"); |
| @@ -955,7 +859,6 @@ fn sweep_blocking(work_dir: &Path, map: &IdMap, helper: &Path) { | |||
| 955 | } | 859 | } |
| 956 | } | 860 | } |
| 957 | 861 | ||
| 958 | -/// 26 Crockford base32 digits, the shape of every job id the forge hands out. | ||
| 959 | fn is_ulid(name: &str) -> bool { | 862 | fn is_ulid(name: &str) -> bool { |
| 960 | name.len() == 26 | 863 | name.len() == 26 |
| 961 | && name | 864 | && name |
| @@ -963,7 +866,6 @@ fn is_ulid(name: &str) -> bool { | |||
| 963 | .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b))) | 866 | .all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b))) |
| 964 | } | 867 | } |
| 965 | 868 | ||
| 966 | -/// The names of the dirs in `dir` that are valid job ids. Symlinks are skipped. | ||
| 967 | fn job_ids_in(dir: &Path) -> Vec<String> { | 869 | fn job_ids_in(dir: &Path) -> Vec<String> { |
| 968 | let Ok(entries) = fs::read_dir(dir) else { | 870 | let Ok(entries) = fs::read_dir(dir) else { |
| 969 | return Vec::new(); | 871 | return Vec::new(); |
| @@ -976,9 +878,6 @@ fn job_ids_in(dir: &Path) -> Vec<String> { | |||
| 976 | .collect() | 878 | .collect() |
| 977 | } | 879 | } |
| 978 | 880 | ||
| 979 | -/// Removes a job dir under `map`. Its files may be owned by subordinate ids, so this goes through | ||
| 980 | -/// the helper in subuid mode (see [`remove_tree`]). The removal blocks, so it runs off the async | ||
| 981 | -/// runtime. | ||
| 982 | async fn remove_job_dir(map: &IdMap, helper: &Path, job_dir: &Path) -> std::io::Result<()> { | 881 | async fn remove_job_dir(map: &IdMap, helper: &Path, job_dir: &Path) -> std::io::Result<()> { |
| 983 | let (map, helper, job_dir) = (map.clone(), helper.to_owned(), job_dir.to_owned()); | 882 | let (map, helper, job_dir) = (map.clone(), helper.to_owned(), job_dir.to_owned()); |
| 984 | tokio::task::spawn_blocking(move || remove_tree(&map, &job_dir, &helper)) | 883 | tokio::task::spawn_blocking(move || remove_tree(&map, &job_dir, &helper)) |
| @@ -1051,7 +950,6 @@ mod tests { | |||
| 1051 | .expect("invocation"); | 950 | .expect("invocation"); |
| 1052 | assert!(inv.args.iter().all(|a| !a.contains(SECRET))); | 951 | assert!(inv.args.iter().all(|a| !a.contains(SECRET))); |
| 1053 | assert!(inv.args.iter().all(|a| !a.contains("visible"))); | 952 | assert!(inv.args.iter().all(|a| !a.contains("visible"))); |
| 1054 | - // The values travel in the child env, by name. | ||
| 1055 | assert!( | 953 | assert!( |
| 1056 | inv.env | 954 | inv.env |
| 1057 | .contains(&("MY_TOKEN".to_owned(), SECRET.to_owned())) | 955 | .contains(&("MY_TOKEN".to_owned(), SECRET.to_owned())) |
| @@ -1108,7 +1006,6 @@ mod tests { | |||
| 1108 | job.memory_bytes = Some(4 << 30); | 1006 | job.memory_bytes = Some(4 << 30); |
| 1109 | let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv"); | 1007 | let inv = podman_invocation(&job, Path::new("/w"), &Limits::default()).expect("inv"); |
| 1110 | let joined = inv.args.join(" "); | 1008 | let joined = inv.args.join(" "); |
| 1111 | - // 4 GiB plus the 256 MiB slack, and no swap on top. | ||
| 1112 | let limit = (4u64 << 30) + (256 << 20); | 1009 | let limit = (4u64 << 30) + (256 << 20); |
| 1113 | assert!( | 1010 | assert!( |
| 1114 | joined.contains(&format!("--memory {limit} --memory-swap {limit}")), | 1011 | joined.contains(&format!("--memory {limit} --memory-swap {limit}")), |
| @@ -1166,7 +1063,6 @@ mod tests { | |||
| 1166 | assert_eq!(podman.outcome, Outcome::Error); | 1063 | assert_eq!(podman.outcome, Outcome::Error); |
| 1167 | } | 1064 | } |
| 1168 | 1065 | ||
| 1169 | - /// Needs rootless podman and network access to pull the image. | ||
| 1170 | #[tokio::test] | 1066 | #[tokio::test] |
| 1171 | #[ignore = "requires rootless podman and registry access"] | 1067 | #[ignore = "requires rootless podman and registry access"] |
| 1172 | async fn podman_runs_a_real_container() { | 1068 | async fn podman_runs_a_real_container() { |
crates/forge-runner/src/lib.rsmodified+12 -13
| @@ -1,27 +1,26 @@ | |||
| 1 | //! The forge CI runner: claims jobs from a forge over HTTPS and runs them in a rootless sandbox | 1 | //! The forge CI runner: claims jobs from a forge over HTTPS and runs them in a rootless sandbox |
| 2 | //! (builtin) or rootless podman. | 2 | //! (builtin) or rootless podman. |
| 3 | //! | 3 | //! |
| 4 | -//! The binaries are thin wrappers over [`cli`] and these modules. They are public so that the | 4 | +//! The binaries are thin wrappers over [`cli`] and these modules. |
| 5 | -//! forge's end-to-end tests can drive a runner with `HostExecutor`. | ||
| 6 | 5 | ||
| 7 | -pub mod artifacts; | 6 | +pub(crate) mod artifacts; |
| 8 | -pub mod cache; | 7 | +pub(crate) mod cache; |
| 9 | pub mod check; | 8 | pub mod check; |
| 10 | pub mod cli; | 9 | pub mod cli; |
| 11 | pub mod client; | 10 | pub mod client; |
| 12 | pub mod config; | 11 | pub mod config; |
| 13 | -pub mod disk; | 12 | +pub(crate) mod disk; |
| 14 | pub mod executor; | 13 | pub mod executor; |
| 15 | -pub mod limiter; | 14 | +pub(crate) mod limiter; |
| 16 | pub mod logs; | 15 | pub mod logs; |
| 17 | -pub mod memory; | 16 | +pub(crate) mod memory; |
| 18 | -pub mod metrics; | 17 | +pub(crate) mod metrics; |
| 19 | pub mod oci; | 18 | pub mod oci; |
| 20 | pub mod oom; | 19 | pub mod oom; |
| 21 | -pub mod pressure; | 20 | +pub(crate) mod pressure; |
| 22 | -pub mod restart; | 21 | +pub(crate) mod restart; |
| 23 | pub mod runner; | 22 | pub mod runner; |
| 24 | pub mod sandbox; | 23 | pub mod sandbox; |
| 25 | -pub mod selflog; | 24 | +pub(crate) mod selflog; |
| 26 | -pub mod update; | 25 | +pub(crate) mod update; |
| 27 | -pub mod workspace; | 26 | +pub(crate) mod workspace; |
crates/forge-runner/src/logs.rsmodified+5 -3
| @@ -295,11 +295,13 @@ where | |||
| 295 | Ok(b) if !b.is_empty() => b, | 295 | Ok(b) if !b.is_empty() => b, |
| 296 | _ => break, | 296 | _ => break, |
| 297 | }; | 297 | }; |
| 298 | - let (take, done) = match available.iter().position(|&b| b == b'\n') { | 298 | + let room = MAX_LINE - line.len(); |
| 299 | + let window = &available[..available.len().min(room)]; | ||
| 300 | + let (take, done) = match window.iter().position(|&b| b == b'\n') { | ||
| 299 | Some(i) => (i + 1, true), | 301 | Some(i) => (i + 1, true), |
| 300 | - None => (available.len(), false), | 302 | + None => (window.len(), false), |
| 301 | }; | 303 | }; |
| 302 | - line.extend_from_slice(&available[..take]); | 304 | + line.extend_from_slice(&window[..take]); |
| 303 | (take, done) | 305 | (take, done) |
| 304 | }; | 306 | }; |
| 305 | reader.consume(take); | 307 | reader.consume(take); |
crates/forge-runner/src/memory.rsmodified+41 -64
| @@ -17,12 +17,6 @@ const FALLBACK_RESERVE: u64 = 1 << 30; | |||
| 17 | /// The smallest budget the runner will run with, so a typo cannot stop it from taking any job. | 17 | /// The smallest budget the runner will run with, so a typo cannot stop it from taking any job. |
| 18 | const MIN_BUDGET: u64 = 256 << 20; | 18 | const MIN_BUDGET: u64 = 256 << 20; |
| 19 | 19 | ||
| 20 | -/// Pure admission rule: a job fits when the running jobs' reservations plus its own stay within | ||
| 21 | -/// the budget. | ||
| 22 | -pub fn fits(reserved: u64, request: u64, budget: u64) -> bool { | ||
| 23 | - reserved.saturating_add(request) <= budget | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | /// What a job reserves: its declared memory or the default, never more than the budget. A job | 20 | /// What a job reserves: its declared memory or the default, never more than the budget. A job |
| 27 | /// bigger than the whole budget therefore still runs, alone, instead of waiting forever. | 21 | /// bigger than the whole budget therefore still runs, alone, instead of waiting forever. |
| 28 | pub fn reservation(declared: Option<u64>, default_reserve: u64, budget: u64) -> u64 { | 22 | pub fn reservation(declared: Option<u64>, default_reserve: u64, budget: u64) -> u64 { |
| @@ -39,37 +33,48 @@ pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent: | |||
| 39 | ram.saturating_add(swap).max(MIN_BUDGET) | 33 | ram.saturating_add(swap).max(MIN_BUDGET) |
| 40 | } | 34 | } |
| 41 | 35 | ||
| 42 | -/// `(MemTotal, SwapTotal)` of a `/proc/meminfo` text, in bytes. | 36 | +/// The fields of a `/proc/meminfo` text the runner reads, in bytes. A missing field is `None`. |
| 43 | -pub fn parse_meminfo(text: &str) -> (Option<u64>, Option<u64>) { | 37 | +#[derive(Default)] |
| 38 | +pub struct Meminfo { | ||
| 39 | + pub total: Option<u64>, | ||
| 40 | + pub available: Option<u64>, | ||
| 41 | + pub swap_total: Option<u64>, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// Parses a `/proc/meminfo` text. The file reports kibibytes. | ||
| 45 | +pub fn meminfo(text: &str) -> Meminfo { | ||
| 44 | let find = |key: &str| { | 46 | let find = |key: &str| { |
| 45 | let line = text.lines().find(|l| l.starts_with(key))?; | 47 | let line = text.lines().find(|l| l.starts_with(key))?; |
| 46 | let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; | 48 | let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; |
| 47 | kib.checked_mul(1024) | 49 | kib.checked_mul(1024) |
| 48 | }; | 50 | }; |
| 49 | - (find("MemTotal:"), find("SwapTotal:")) | 51 | + Meminfo { |
| 52 | + total: find("MemTotal:"), | ||
| 53 | + available: find("MemAvailable:"), | ||
| 54 | + swap_total: find("SwapTotal:"), | ||
| 55 | + } | ||
| 50 | } | 56 | } |
| 51 | 57 | ||
| 52 | -fn host_memory() -> (Option<u64>, Option<u64>) { | 58 | +fn host_memory() -> Meminfo { |
| 53 | std::fs::read_to_string("/proc/meminfo") | 59 | std::fs::read_to_string("/proc/meminfo") |
| 54 | - .map(|t| parse_meminfo(&t)) | 60 | + .map(|t| meminfo(&t)) |
| 55 | - .unwrap_or((None, None)) | 61 | + .unwrap_or_default() |
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// A budget set in `runner.toml` or by the forge. `None` in `auto` mode. | ||
| 65 | +fn fixed_budget(limits: &Limits) -> Option<u64> { | ||
| 66 | + limits.memory_budget.as_deref().and_then(parse_size) | ||
| 56 | } | 67 | } |
| 57 | 68 | ||
| 58 | /// The budget `limits` asks for on a host with this much memory and swap. | 69 | /// The budget `limits` asks for on a host with this much memory and swap. |
| 59 | fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 { | 70 | fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 { |
| 60 | - match limits.memory_budget.as_deref() { | 71 | + fixed_budget(limits).map_or_else( |
| 61 | - None | Some("auto") => { | 72 | + || { |
| 62 | let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); | 73 | let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); |
| 63 | auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) | 74 | auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) |
| 64 | - } | 75 | + }, |
| 65 | - Some(text) => parse_size(text).map_or_else( | 76 | + |n| n.max(MIN_BUDGET), |
| 66 | - || { | 77 | + ) |
| 67 | - let headroom = parse_size(&limits.memory_headroom).unwrap_or(1 << 30); | ||
| 68 | - auto_budget(mem_total, swap_total, headroom, limits.budget_swap_percent) | ||
| 69 | - }, | ||
| 70 | - |n| n.max(MIN_BUDGET), | ||
| 71 | - ), | ||
| 72 | - } | ||
| 73 | } | 78 | } |
| 74 | 79 | ||
| 75 | struct State { | 80 | struct State { |
| @@ -82,11 +87,7 @@ struct State { | |||
| 82 | /// The part of the budget that is swap: `swap_percent` of the swap in `auto` mode, none with a set | 87 | /// The part of the budget that is swap: `swap_percent` of the swap in `auto` mode, none with a set |
| 83 | /// budget. A lone job may use it as swap on top of the rest of the budget, which is RAM. | 88 | /// budget. A lone job may use it as swap on top of the rest of the budget, which is RAM. |
| 84 | fn swap_share(limits: &Limits, swap_total: u64) -> u64 { | 89 | fn swap_share(limits: &Limits, swap_total: u64) -> u64 { |
| 85 | - let set = limits | 90 | + if fixed_budget(limits).is_some() { |
| 86 | - .memory_budget | ||
| 87 | - .as_deref() | ||
| 88 | - .is_some_and(|text| text != "auto" && parse_size(text).is_some()); | ||
| 89 | - if set { | ||
| 90 | return 0; | 91 | return 0; |
| 91 | } | 92 | } |
| 92 | (u128::from(swap_total) * u128::from(limits.budget_swap_percent.min(100)) / 100) as u64 | 93 | (u128::from(swap_total) * u128::from(limits.budget_swap_percent.min(100)) / 100) as u64 |
| @@ -106,12 +107,6 @@ pub struct Reservation { | |||
| 106 | gate: Arc<MemoryGate>, | 107 | gate: Arc<MemoryGate>, |
| 107 | } | 108 | } |
| 108 | 109 | ||
| 109 | -impl Reservation { | ||
| 110 | - pub fn bytes(&self) -> u64 { | ||
| 111 | - self.bytes | ||
| 112 | - } | ||
| 113 | -} | ||
| 114 | - | ||
| 115 | impl Drop for Reservation { | 110 | impl Drop for Reservation { |
| 116 | fn drop(&mut self) { | 111 | fn drop(&mut self) { |
| 117 | let mut state = self.gate.lock(); | 112 | let mut state = self.gate.lock(); |
| @@ -123,8 +118,12 @@ impl MemoryGate { | |||
| 123 | /// A gate for this host, read from `/proc/meminfo`. Without it the host is assumed to have | 118 | /// A gate for this host, read from `/proc/meminfo`. Without it the host is assumed to have |
| 124 | /// 8 GiB. | 119 | /// 8 GiB. |
| 125 | pub fn for_host(limits: &Limits) -> Arc<Self> { | 120 | pub fn for_host(limits: &Limits) -> Arc<Self> { |
| 126 | - let (mem, swap) = host_memory(); | 121 | + let host = host_memory(); |
| 127 | - Self::new(limits, mem.unwrap_or(8 << 30), swap.unwrap_or(0)) | 122 | + Self::new( |
| 123 | + limits, | ||
| 124 | + host.total.unwrap_or(8 << 30), | ||
| 125 | + host.swap_total.unwrap_or(0), | ||
| 126 | + ) | ||
| 128 | } | 127 | } |
| 129 | 128 | ||
| 130 | pub fn new(limits: &Limits, mem_total: u64, swap_total: u64) -> Arc<Self> { | 129 | pub fn new(limits: &Limits, mem_total: u64, swap_total: u64) -> Arc<Self> { |
| @@ -166,10 +165,6 @@ impl MemoryGate { | |||
| 166 | self.lock().reserve | 165 | self.lock().reserve |
| 167 | } | 166 | } |
| 168 | 167 | ||
| 169 | - pub fn reserved(&self) -> u64 { | ||
| 170 | - self.lock().reserved | ||
| 171 | - } | ||
| 172 | - | ||
| 173 | /// What a new claim may admit: the budget minus the running jobs' reservations. | 168 | /// What a new claim may admit: the budget minus the running jobs' reservations. |
| 174 | pub fn free(&self) -> u64 { | 169 | pub fn free(&self) -> u64 { |
| 175 | let state = self.lock(); | 170 | let state = self.lock(); |
| @@ -250,28 +245,11 @@ mod tests { | |||
| 250 | assert_eq!(MemoryGate::new(&set, 8 * GIB, 8 * GIB).swap(), 0); | 245 | assert_eq!(MemoryGate::new(&set, 8 * GIB, 8 * GIB).swap(), 0); |
| 251 | } | 246 | } |
| 252 | 247 | ||
| 253 | - #[test] | ||
| 254 | - fn a_job_fits_when_the_sum_stays_within_the_budget() { | ||
| 255 | - // 6.5 GiB budget, one 4 GiB job running. | ||
| 256 | - let budget = 6 * GIB + GIB / 2; | ||
| 257 | - assert!(fits(0, 4 * GIB, budget)); | ||
| 258 | - assert!(fits(4 * GIB, 2 * GIB, budget)); | ||
| 259 | - assert!( | ||
| 260 | - fits(4 * GIB, 2 * GIB + GIB / 2, budget), | ||
| 261 | - "exactly the budget" | ||
| 262 | - ); | ||
| 263 | - assert!(!fits(4 * GIB, 4 * GIB, budget), "second heavy job waits"); | ||
| 264 | - assert!(!fits(budget, 1, budget)); | ||
| 265 | - assert!(!fits(u64::MAX, 1, budget), "no overflow"); | ||
| 266 | - } | ||
| 267 | - | ||
| 268 | #[test] | 248 | #[test] |
| 269 | fn a_job_without_memory_reserves_the_default() { | 249 | fn a_job_without_memory_reserves_the_default() { |
| 270 | assert_eq!(reservation(None, GIB, 6 * GIB), GIB); | 250 | assert_eq!(reservation(None, GIB, 6 * GIB), GIB); |
| 271 | assert_eq!(reservation(Some(4 * GIB), GIB, 6 * GIB), 4 * GIB); | 251 | assert_eq!(reservation(Some(4 * GIB), GIB, 6 * GIB), 4 * GIB); |
| 272 | - // Bigger than the whole budget: capped, so it still runs when the runner is idle. | ||
| 273 | assert_eq!(reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB); | 252 | assert_eq!(reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB); |
| 274 | - assert!(fits(0, reservation(Some(64 * GIB), GIB, 6 * GIB), 6 * GIB)); | ||
| 275 | } | 253 | } |
| 276 | 254 | ||
| 277 | #[test] | 255 | #[test] |
| @@ -291,12 +269,12 @@ mod tests { | |||
| 291 | 269 | ||
| 292 | #[test] | 270 | #[test] |
| 293 | fn meminfo_is_parsed() { | 271 | fn meminfo_is_parsed() { |
| 294 | - let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nSwapTotal: 8388604 kB\n"; | 272 | + let text = "MemTotal: 7971680 kB\nMemFree: 1 kB\nMemAvailable: 4000000 kB\nSwapTotal: 8388604 kB\n"; |
| 295 | - assert_eq!( | 273 | + let m = meminfo(text); |
| 296 | - parse_meminfo(text), | 274 | + assert_eq!(m.total, Some(7_971_680 * 1024)); |
| 297 | - (Some(7_971_680 * 1024), Some(8_388_604 * 1024)) | 275 | + assert_eq!(m.available, Some(4_000_000 * 1024)); |
| 298 | - ); | 276 | + assert_eq!(m.swap_total, Some(8_388_604 * 1024)); |
| 299 | - assert_eq!(parse_meminfo(""), (None, None)); | 277 | + assert_eq!(meminfo("").total, None); |
| 300 | } | 278 | } |
| 301 | 279 | ||
| 302 | #[test] | 280 | #[test] |
| @@ -311,7 +289,6 @@ mod tests { | |||
| 311 | let heavy = gate.reserve(Some(4 * GIB)); | 289 | let heavy = gate.reserve(Some(4 * GIB)); |
| 312 | assert_eq!(gate.free(), 2 * GIB); | 290 | assert_eq!(gate.free(), 2 * GIB); |
| 313 | let light = gate.reserve(None); | 291 | let light = gate.reserve(None); |
| 314 | - assert_eq!(gate.reserved(), 5 * GIB); | ||
| 315 | assert_eq!(gate.free(), GIB); | 292 | assert_eq!(gate.free(), GIB); |
| 316 | drop(heavy); | 293 | drop(heavy); |
| 317 | assert_eq!(gate.free(), 5 * GIB); | 294 | assert_eq!(gate.free(), 5 * GIB); |
crates/forge-runner/src/metrics.rsmodified+2 -17
| @@ -55,16 +55,6 @@ pub fn parse_cpu(text: &str) -> Option<(u64, u64)> { | |||
| 55 | Some((total.saturating_sub(idle), total)) | 55 | Some((total.saturating_sub(idle), total)) |
| 56 | } | 56 | } |
| 57 | 57 | ||
| 58 | -/// `(MemTotal, MemAvailable)` of `/proc/meminfo`, in bytes. The file reports kibibytes. | ||
| 59 | -pub fn parse_mem(text: &str) -> Option<(u64, u64)> { | ||
| 60 | - let find = |key: &str| { | ||
| 61 | - let line = text.lines().find(|l| l.starts_with(key))?; | ||
| 62 | - let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; | ||
| 63 | - kib.checked_mul(1024) | ||
| 64 | - }; | ||
| 65 | - Some((find("MemTotal:")?, find("MemAvailable:")?)) | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | /// `(rx, tx)` bytes summed over the interfaces of `/proc/net/dev` except `lo`. The two header | 58 | /// `(rx, tx)` bytes summed over the interfaces of `/proc/net/dev` except `lo`. The two header |
| 69 | /// lines have no colon and are skipped. | 59 | /// lines have no colon and are skipped. |
| 70 | pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> { | 60 | pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> { |
| @@ -99,7 +89,8 @@ pub fn read_snapshot(work_dir: &Path) -> Option<Snapshot> { | |||
| 99 | let mem = std::fs::read_to_string("/proc/meminfo").ok()?; | 89 | let mem = std::fs::read_to_string("/proc/meminfo").ok()?; |
| 100 | let net = std::fs::read_to_string("/proc/net/dev").ok()?; | 90 | let net = std::fs::read_to_string("/proc/net/dev").ok()?; |
| 101 | let (busy, total) = parse_cpu(&stat)?; | 91 | let (busy, total) = parse_cpu(&stat)?; |
| 102 | - let (mem_total, mem_available) = parse_mem(&mem)?; | 92 | + let info = crate::memory::meminfo(&mem); |
| 93 | + let (mem_total, mem_available) = (info.total?, info.available?); | ||
| 103 | let (rx, tx) = parse_net_dev(&net)?; | 94 | let (rx, tx) = parse_net_dev(&net)?; |
| 104 | let (disk_used, disk_total) = disk_usage(work_dir).unwrap_or((0, 0)); | 95 | let (disk_used, disk_total) = disk_usage(work_dir).unwrap_or((0, 0)); |
| 105 | Some(Snapshot { | 96 | Some(Snapshot { |
| @@ -230,12 +221,6 @@ mod tests { | |||
| 230 | assert_eq!(parse_cpu(text), Some((170, 1010))); | 221 | assert_eq!(parse_cpu(text), Some((170, 1010))); |
| 231 | } | 222 | } |
| 232 | 223 | ||
| 233 | - #[test] | ||
| 234 | - fn mem_reads_total_and_available_in_bytes() { | ||
| 235 | - let text = "MemTotal: 16000000 kB\nMemFree: 1000000 kB\nMemAvailable: 4000000 kB\n"; | ||
| 236 | - assert_eq!(parse_mem(text), Some((16_000_000 * 1024, 4_000_000 * 1024))); | ||
| 237 | - } | ||
| 238 | - | ||
| 239 | #[test] | 224 | #[test] |
| 240 | fn net_sums_every_interface_but_loopback() { | 225 | fn net_sums_every_interface_but_loopback() { |
| 241 | let text = "Inter-| Receive | Transmit\n \ | 226 | let text = "Inter-| Receive | Transmit\n \ |
crates/forge-runner/src/oci/pull.rsmodified+5 -18
| @@ -1,7 +1,6 @@ | |||
| 1 | //! Resolving an image reference, pulling its manifest and layers, and unpacking them. | 1 | //! Resolving an image reference, pulling its manifest and layers, and unpacking them. |
| 2 | 2 | ||
| 3 | use std::fs::{self, Permissions}; | 3 | use std::fs::{self, Permissions}; |
| 4 | -use std::io::{self, Read}; | ||
| 5 | use std::os::unix::fs::PermissionsExt; | 4 | use std::os::unix::fs::PermissionsExt; |
| 6 | use std::path::PathBuf; | 5 | use std::path::PathBuf; |
| 7 | 6 | ||
| @@ -148,7 +147,10 @@ impl ImageStore { | |||
| 148 | fs::set_permissions(staging.path(), Permissions::from_mode(0o755))?; | 147 | fs::set_permissions(staging.path(), Permissions::from_mode(0o755))?; |
| 149 | let unpacked = staging.keep(); | 148 | let unpacked = staging.keep(); |
| 150 | let final_dir = self.rootfs_path(&hex); | 149 | let final_dir = self.rootfs_path(&hex); |
| 151 | - if let Err(err) = fs::rename(&unpacked, &final_dir) { | 150 | + if let Err(err) = self |
| 151 | + .remove_entry(&final_dir) | ||
| 152 | + .and_then(|()| fs::rename(&unpacked, &final_dir)) | ||
| 153 | + { | ||
| 152 | let _ = self.remove_entry(&unpacked); | 154 | let _ = self.remove_entry(&unpacked); |
| 153 | return Err(err.into()); | 155 | return Err(err.into()); |
| 154 | } | 156 | } |
| @@ -285,23 +287,8 @@ fn verify_bytes(bytes: &[u8], digest: &str) -> Result<(), ImageError> { | |||
| 285 | } | 287 | } |
| 286 | } | 288 | } |
| 287 | 289 | ||
| 288 | -/// Hashes a file on a blocking thread and returns the hex digest. | ||
| 289 | async fn sha256_file(path: PathBuf) -> Result<String, ImageError> { | 290 | async fn sha256_file(path: PathBuf) -> Result<String, ImageError> { |
| 290 | - let hash = tokio::task::spawn_blocking(move || -> io::Result<String> { | 291 | + Ok(tokio::task::spawn_blocking(move || crate::update::file_sha256(&path)).await??) |
| 291 | - let mut file = fs::File::open(&path)?; | ||
| 292 | - let mut hasher = Sha256::new(); | ||
| 293 | - let mut buf = vec![0u8; 64 * 1024]; | ||
| 294 | - loop { | ||
| 295 | - let n = file.read(&mut buf)?; | ||
| 296 | - if n == 0 { | ||
| 297 | - break; | ||
| 298 | - } | ||
| 299 | - hasher.update(&buf[..n]); | ||
| 300 | - } | ||
| 301 | - Ok(hex::encode(hasher.finalize())) | ||
| 302 | - }) | ||
| 303 | - .await??; | ||
| 304 | - Ok(hash) | ||
| 305 | } | 292 | } |
| 306 | 293 | ||
| 307 | /// Sends one line to the job log. A closed log channel is not an error for the pull. | 294 | /// Sends one line to the job log. A closed log channel is not an error for the pull. |
crates/forge-runner/src/oci/store.rsmodified+14 -6
| @@ -302,9 +302,9 @@ fn older_than(time: SystemTime, now: SystemTime, max_age: Duration) -> bool { | |||
| 302 | /// The rootfs dir name for `hex`: `<hex>` in single mode, and `<hex>-s<start>-<n>` for a subuid | 302 | /// The rootfs dir name for `hex`: `<hex>` in single mode, and `<hex>-s<start>-<n>` for a subuid |
| 303 | /// range, so each range has its own unpacked tree. | 303 | /// range, so each range has its own unpacked tree. |
| 304 | fn rootfs_dir_name(map: &IdMap, hex: &str) -> String { | 304 | fn rootfs_dir_name(map: &IdMap, hex: &str) -> String { |
| 305 | - match map.sub_uid { | 305 | + match map.sub { |
| 306 | - Some((start, n)) if map.is_subuid() => format!("{hex}-s{start}-{n}"), | 306 | + Some(s) => format!("{hex}-s{}-{}", s.uid_start, s.count), |
| 307 | - _ => hex.to_owned(), | 307 | + None => hex.to_owned(), |
| 308 | } | 308 | } |
| 309 | } | 309 | } |
| 310 | 310 | ||
| @@ -318,6 +318,7 @@ fn remove_file_if_exists(path: &Path) -> io::Result<()> { | |||
| 318 | #[cfg(test)] | 318 | #[cfg(test)] |
| 319 | mod tests { | 319 | mod tests { |
| 320 | use super::*; | 320 | use super::*; |
| 321 | + use crate::sandbox::idmap::SubRange; | ||
| 321 | 322 | ||
| 322 | #[test] | 323 | #[test] |
| 323 | fn rootfs_dir_names_follow_the_mode() { | 324 | fn rootfs_dir_names_follow_the_mode() { |
| @@ -326,15 +327,22 @@ mod tests { | |||
| 326 | let subuid = IdMap { | 327 | let subuid = IdMap { |
| 327 | uid: 1000, | 328 | uid: 1000, |
| 328 | gid: 1000, | 329 | gid: 1000, |
| 329 | - sub_uid: Some((524_288, 65_536)), | 330 | + sub: Some(SubRange { |
| 330 | - sub_gid: Some((524_288, 65_536)), | 331 | + uid_start: 524_288, |
| 332 | + gid_start: 524_288, | ||
| 333 | + count: 65_536, | ||
| 334 | + }), | ||
| 331 | }; | 335 | }; |
| 332 | assert_eq!( | 336 | assert_eq!( |
| 333 | rootfs_dir_name(&subuid, &hex), | 337 | rootfs_dir_name(&subuid, &hex), |
| 334 | format!("{hex}-s524288-65536") | 338 | format!("{hex}-s524288-65536") |
| 335 | ); | 339 | ); |
| 336 | let other_range = IdMap { | 340 | let other_range = IdMap { |
| 337 | - sub_uid: Some((600_000, 65_536)), | 341 | + sub: Some(SubRange { |
| 342 | + uid_start: 600_000, | ||
| 343 | + gid_start: 524_288, | ||
| 344 | + count: 65_536, | ||
| 345 | + }), | ||
| 338 | ..subuid | 346 | ..subuid |
| 339 | }; | 347 | }; |
| 340 | assert_ne!( | 348 | assert_ne!( |
crates/forge-runner/src/pressure.rsmodified+30 -57
| @@ -65,14 +65,16 @@ pub enum Cause { | |||
| 65 | 65 | ||
| 66 | // ----- pure rules ----- | 66 | // ----- pure rules ----- |
| 67 | 67 | ||
| 68 | +fn field_u64(text: &str, key: &str) -> Option<u64> { | ||
| 69 | + text.lines().find_map(|line| { | ||
| 70 | + let (k, v) = line.split_once(' ')?; | ||
| 71 | + (k == key).then(|| v.trim().parse().ok())? | ||
| 72 | + }) | ||
| 73 | +} | ||
| 74 | + | ||
| 68 | /// The `high` counter of a `memory.events` text. Missing means 0. | 75 | /// The `high` counter of a `memory.events` text. Missing means 0. |
| 69 | pub fn parse_high(text: &str) -> u64 { | 76 | pub fn parse_high(text: &str) -> u64 { |
| 70 | - text.lines() | 77 | + field_u64(text, "high").unwrap_or(0) |
| 71 | - .find_map(|line| { | ||
| 72 | - let (key, value) = line.split_once(' ')?; | ||
| 73 | - (key == "high").then(|| value.trim().parse().ok())? | ||
| 74 | - }) | ||
| 75 | - .unwrap_or(0) | ||
| 76 | } | 78 | } |
| 77 | 79 | ||
| 78 | /// `memory.high` of the box, or `None` for `max`. Only set while two or more jobs run unfrozen: | 80 | /// `memory.high` of the box, or `None` for `max`. Only set while two or more jobs run unfrozen: |
| @@ -82,24 +84,18 @@ pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> { | |||
| 82 | return None; | 84 | return None; |
| 83 | } | 85 | } |
| 84 | let margin = HIGH_MARGIN_MIN.max(budget / 20); | 86 | let margin = HIGH_MARGIN_MIN.max(budget / 20); |
| 85 | - Some(budget.saturating_sub(margin)) | 87 | + Some(budget.saturating_sub(margin).max(budget / 2)) |
| 86 | -} | ||
| 87 | - | ||
| 88 | -/// A running job, as far as victim choice cares. | ||
| 89 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 90 | -pub struct Running { | ||
| 91 | - /// Start order: higher is younger. | ||
| 92 | - pub seq: u64, | ||
| 93 | - pub frozen: bool, | ||
| 94 | } | 88 | } |
| 95 | 89 | ||
| 96 | -/// The job to park: the youngest unfrozen one, and only while at least two are unfrozen. | 90 | +/// The job to park: the youngest, and only while at least two run. |
| 97 | -pub fn pick_victim(jobs: &[Running]) -> Option<usize> { | 91 | +pub fn pick_victim(seqs: &[u64]) -> Option<usize> { |
| 98 | - let unfrozen = || jobs.iter().enumerate().filter(|(_, j)| !j.frozen); | 92 | + if seqs.len() < 2 { |
| 99 | - if unfrozen().count() < 2 { | ||
| 100 | return None; | 93 | return None; |
| 101 | } | 94 | } |
| 102 | - unfrozen().max_by_key(|(_, j)| j.seq).map(|(i, _)| i) | 95 | + seqs.iter() |
| 96 | + .enumerate() | ||
| 97 | + .max_by_key(|(_, seq)| **seq) | ||
| 98 | + .map(|(i, _)| i) | ||
| 103 | } | 99 | } |
| 104 | 100 | ||
| 105 | /// A parked job, as far as thaw choice cares. | 101 | /// A parked job, as far as thaw choice cares. |
| @@ -197,12 +193,7 @@ impl Registration { | |||
| 197 | self.handle.requeued.load(Ordering::SeqCst) | 193 | self.handle.requeued.load(Ordering::SeqCst) |
| 198 | } | 194 | } |
| 199 | 195 | ||
| 200 | - /// How long the job has spent frozen so far. Its timeout does not count that time. | 196 | + /// A handle for reading [`JobHandle::paused`] from another task. |
| 201 | - pub fn paused(&self) -> Duration { | ||
| 202 | - self.handle.paused() | ||
| 203 | - } | ||
| 204 | - | ||
| 205 | - /// A handle for reading [`Registration::paused`] from another task. | ||
| 206 | pub fn pause_clock(&self) -> Arc<JobHandle> { | 197 | pub fn pause_clock(&self) -> Arc<JobHandle> { |
| 207 | self.handle.clone() | 198 | self.handle.clone() |
| 208 | } | 199 | } |
| @@ -263,12 +254,8 @@ impl Pressure { | |||
| 263 | create_box(&parent, budget) | 254 | create_box(&parent, budget) |
| 264 | }) | 255 | }) |
| 265 | .await; | 256 | .await; |
| 266 | - let dir = match setup { | 257 | + let dir = match setup.map_err(|e| e.to_string()).and_then(|r| r) { |
| 267 | - Ok(Ok(dir)) => dir, | 258 | + Ok(dir) => dir, |
| 268 | - Ok(Err(e)) => { | ||
| 269 | - tracing::warn!("memory control is off: {e}"); | ||
| 270 | - return None; | ||
| 271 | - } | ||
| 272 | Err(e) => { | 259 | Err(e) => { |
| 273 | tracing::warn!("memory control is off: {e}"); | 260 | tracing::warn!("memory control is off: {e}"); |
| 274 | return None; | 261 | return None; |
| @@ -446,14 +433,8 @@ impl Pressure { | |||
| 446 | let live: Vec<usize> = (0..state.entries.len()) | 433 | let live: Vec<usize> = (0..state.entries.len()) |
| 447 | .filter(|&i| is_live(&state.entries[i])) | 434 | .filter(|&i| is_live(&state.entries[i])) |
| 448 | .collect(); | 435 | .collect(); |
| 449 | - let running: Vec<Running> = live | 436 | + let seqs: Vec<u64> = live.iter().map(|&i| state.entries[i].seq).collect(); |
| 450 | - .iter() | 437 | + if let Some(pick) = pick_victim(&seqs) { |
| 451 | - .map(|&i| Running { | ||
| 452 | - seq: state.entries[i].seq, | ||
| 453 | - frozen: false, | ||
| 454 | - }) | ||
| 455 | - .collect(); | ||
| 456 | - if let Some(pick) = pick_victim(&running) { | ||
| 457 | let victim = live[pick]; | 438 | let victim = live[pick]; |
| 458 | let waiting_for = live | 439 | let waiting_for = live |
| 459 | .iter() | 440 | .iter() |
| @@ -626,10 +607,7 @@ fn read_u64(dir: &Path, file: &str) -> Option<u64> { | |||
| 626 | 607 | ||
| 627 | fn stat_field(dir: &Path, key: &str) -> Option<u64> { | 608 | fn stat_field(dir: &Path, key: &str) -> Option<u64> { |
| 628 | let text = fs::read_to_string(dir.join("memory.stat")).ok()?; | 609 | let text = fs::read_to_string(dir.join("memory.stat")).ok()?; |
| 629 | - text.lines().find_map(|line| { | 610 | + field_u64(&text, key) |
| 630 | - let (k, v) = line.split_once(' ')?; | ||
| 631 | - (k == key).then(|| v.trim().parse().ok())? | ||
| 632 | - }) | ||
| 633 | } | 611 | } |
| 634 | 612 | ||
| 635 | fn job_swap(dir: &Path) -> Option<u64> { | 613 | fn job_swap(dir: &Path) -> Option<u64> { |
| @@ -897,20 +875,15 @@ mod tests { | |||
| 897 | assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN)); | 875 | assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN)); |
| 898 | // 5% of 20 GiB is 1 GiB. | 876 | // 5% of 20 GiB is 1 GiB. |
| 899 | assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB)); | 877 | assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB)); |
| 878 | + assert_eq!(high_value(2, 256 << 20), Some(128 << 20)); | ||
| 900 | } | 879 | } |
| 901 | 880 | ||
| 902 | #[test] | 881 | #[test] |
| 903 | - fn victim_is_the_youngest_unfrozen_with_a_partner() { | 882 | + fn victim_is_the_youngest_with_a_partner() { |
| 904 | - let job = |seq, frozen| Running { seq, frozen }; | ||
| 905 | assert_eq!(pick_victim(&[]), None); | 883 | assert_eq!(pick_victim(&[]), None); |
| 906 | - assert_eq!(pick_victim(&[job(1, false)]), None); | 884 | + assert_eq!(pick_victim(&[1]), None); |
| 907 | - assert_eq!(pick_victim(&[job(1, false), job(2, false)]), Some(1)); | 885 | + assert_eq!(pick_victim(&[1, 2]), Some(1)); |
| 908 | - assert_eq!( | 886 | + assert_eq!(pick_victim(&[5, 2, 9]), Some(2)); |
| 909 | - pick_victim(&[job(5, false), job(2, false), job(9, true)]), | ||
| 910 | - Some(0) | ||
| 911 | - ); | ||
| 912 | - // One unfrozen job left: nothing to pause. | ||
| 913 | - assert_eq!(pick_victim(&[job(1, false), job(2, true)]), None); | ||
| 914 | } | 887 | } |
| 915 | 888 | ||
| 916 | #[test] | 889 | #[test] |
| @@ -1045,13 +1018,13 @@ mod tests { | |||
| 1045 | let (_tmp, pressure) = fake_box(GIB); | 1018 | let (_tmp, pressure) = fake_box(GIB); |
| 1046 | let (tx, mut rx) = mpsc::channel(8); | 1019 | let (tx, mut rx) = mpsc::channel(8); |
| 1047 | let reg = pressure.register("a", "build", tx); | 1020 | let reg = pressure.register("a", "build", tx); |
| 1048 | - assert_eq!(reg.paused(), Duration::ZERO); | 1021 | + assert_eq!(reg.handle.paused(), Duration::ZERO); |
| 1049 | reg.handle.pause(); | 1022 | reg.handle.pause(); |
| 1050 | std::thread::sleep(Duration::from_millis(5)); | 1023 | std::thread::sleep(Duration::from_millis(5)); |
| 1051 | - assert!(reg.paused() > Duration::ZERO); | 1024 | + assert!(reg.handle.paused() > Duration::ZERO); |
| 1052 | let lasted = reg.handle.resume(); | 1025 | let lasted = reg.handle.resume(); |
| 1053 | assert!(lasted > Duration::ZERO); | 1026 | assert!(lasted > Duration::ZERO); |
| 1054 | - assert!(reg.paused() >= lasted); | 1027 | + assert!(reg.handle.paused() >= lasted); |
| 1055 | drop(reg); | 1028 | drop(reg); |
| 1056 | // The sender is gone with the registration, so the log shipper can finish. | 1029 | // The sender is gone with the registration, so the log shipper can finish. |
| 1057 | assert!(matches!( | 1030 | assert!(matches!( |
crates/forge-runner/src/runner.rsmodified+11 -75
| @@ -1,5 +1,3 @@ | |||
| 1 | -//! The runner loop: claim a job, run it, ship its logs and artifacts, and report the result. | ||
| 2 | - | ||
| 3 | use std::sync::Arc; | 1 | use std::sync::Arc; |
| 4 | use std::sync::atomic::{AtomicBool, Ordering}; | 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 5 | use std::time::Duration; | 3 | use std::time::Duration; |
| @@ -28,23 +26,16 @@ use crate::selflog; | |||
| 28 | use crate::update::{self, Installed, UpdateState}; | 26 | use crate::update::{self, Installed, UpdateState}; |
| 29 | use crate::workspace; | 27 | use crate::workspace; |
| 30 | 28 | ||
| 31 | -/// Log lines queued between the executor and the log shipper. | ||
| 32 | const LOG_CHANNEL: usize = 64; | 29 | const LOG_CHANNEL: usize = 64; |
| 33 | -/// How many times the runner tries to report a finished job. | ||
| 34 | -/// How long a result is retried while the forge cannot be reached (a restart or a self-update). | ||
| 35 | const FINISH_PATIENCE: Duration = Duration::from_secs(10 * 60); | 30 | const FINISH_PATIENCE: Duration = Duration::from_secs(10 * 60); |
| 36 | -/// Largest single artifact the runner will upload. The forge enforces its own total cap. | ||
| 37 | const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024; | 31 | const MAX_ARTIFACT_BYTES: u64 = 512 * 1024 * 1024; |
| 38 | -/// How long a stopping runner waits for its last log lines to reach the forge. | ||
| 39 | const LOG_FLUSH: Duration = Duration::from_secs(5); | 32 | const LOG_FLUSH: Duration = Duration::from_secs(5); |
| 40 | 33 | ||
| 41 | -/// Timing knobs. Production uses the defaults. Tests shorten them. | ||
| 42 | #[derive(Clone, Copy, Debug)] | 34 | #[derive(Clone, Copy, Debug)] |
| 43 | pub struct RunOptions { | 35 | pub struct RunOptions { |
| 44 | pub heartbeat_every: Duration, | 36 | pub heartbeat_every: Duration, |
| 45 | pub claim_backoff: Duration, | 37 | pub claim_backoff: Duration, |
| 46 | pub pump: PumpConfig, | 38 | pub pump: PumpConfig, |
| 47 | - /// When set, replaces `timeout_minutes` from the job. | ||
| 48 | pub timeout_override: Option<Duration>, | 39 | pub timeout_override: Option<Duration>, |
| 49 | } | 40 | } |
| 50 | 41 | ||
| @@ -59,34 +50,23 @@ impl Default for RunOptions { | |||
| 59 | } | 50 | } |
| 60 | } | 51 | } |
| 61 | 52 | ||
| 62 | -/// How [`Runner::run`] ended. | ||
| 63 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 53 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 64 | pub enum RunEnd { | 54 | pub enum RunEnd { |
| 65 | - /// Shutdown was requested. | ||
| 66 | Stopped, | 55 | Stopped, |
| 67 | - /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`]. | ||
| 68 | Updated, | 56 | Updated, |
| 69 | - /// An admin asked for a restart and the jobs are done. The caller exits with | ||
| 70 | - /// [`update::RESTART_EXIT_CODE`], like for an update. | ||
| 71 | Restart, | 57 | Restart, |
| 72 | } | 58 | } |
| 73 | 59 | ||
| 74 | -/// A runner bound to one forge and one executor. | ||
| 75 | #[derive(Clone)] | 60 | #[derive(Clone)] |
| 76 | pub struct Runner { | 61 | pub struct Runner { |
| 77 | client: ForgeClient, | 62 | client: ForgeClient, |
| 78 | config: Arc<RunnerConfig>, | 63 | config: Arc<RunnerConfig>, |
| 79 | executor: Arc<dyn Executor>, | 64 | executor: Arc<dyn Executor>, |
| 80 | options: RunOptions, | 65 | options: RunOptions, |
| 81 | - /// The build cache, when it is on. See [`CacheStore`]. | ||
| 82 | cache: Option<Arc<CacheStore>>, | 66 | cache: Option<Arc<CacheStore>>, |
| 83 | - /// The live job limit. Starts at `runner.toml` and follows the forge's override. | ||
| 84 | limiter: Arc<Limiter>, | 67 | limiter: Arc<Limiter>, |
| 85 | - /// The memory budget and the running jobs' reservations, see [`crate::memory`]. | ||
| 86 | memory: Arc<MemoryGate>, | 68 | memory: Arc<MemoryGate>, |
| 87 | - /// A restart an admin asked for, see [`restart`]. | ||
| 88 | restart: Arc<RestartState>, | 69 | restart: Arc<RestartState>, |
| 89 | - /// The memory box and its controller, when the host allows it, see [`crate::pressure`]. | ||
| 90 | pressure: Option<Arc<Pressure>>, | 70 | pressure: Option<Arc<Pressure>>, |
| 91 | } | 71 | } |
| 92 | 72 | ||
| @@ -112,14 +92,11 @@ impl Runner { | |||
| 112 | }) | 92 | }) |
| 113 | } | 93 | } |
| 114 | 94 | ||
| 115 | - /// Turns on reactive memory control: jobs are paused under pressure, and no job is claimed | ||
| 116 | - /// while one is parked. | ||
| 117 | pub fn with_pressure(mut self, pressure: Option<Arc<Pressure>>) -> Self { | 95 | pub fn with_pressure(mut self, pressure: Option<Arc<Pressure>>) -> Self { |
| 118 | self.pressure = pressure; | 96 | self.pressure = pressure; |
| 119 | self | 97 | self |
| 120 | } | 98 | } |
| 121 | 99 | ||
| 122 | - /// Turns on the build cache for every job this runner runs. | ||
| 123 | pub fn with_cache(mut self, cache: CacheStore) -> Self { | 100 | pub fn with_cache(mut self, cache: CacheStore) -> Self { |
| 124 | self.cache = Some(Arc::new(cache)); | 101 | self.cache = Some(Arc::new(cache)); |
| 125 | self | 102 | self |
| @@ -129,15 +106,8 @@ impl Runner { | |||
| 129 | &self.client | 106 | &self.client |
| 130 | } | 107 | } |
| 131 | 108 | ||
| 132 | - /// Claims and runs jobs, up to `concurrency` at a time, until `shutdown` is cancelled. Jobs | ||
| 133 | - /// still running at shutdown are cancelled and reported as cancelled. | ||
| 134 | - /// | ||
| 135 | - /// When the forge advertises a different binary and `auto_update` is on, no new jobs are | ||
| 136 | - /// claimed. Once the running jobs finish, the binary is replaced and the loop returns | ||
| 137 | - /// [`RunEnd::Updated`]. | ||
| 138 | pub async fn run(&self, shutdown: CancellationToken) -> RunEnd { | 109 | pub async fn run(&self, shutdown: CancellationToken) -> RunEnd { |
| 139 | let mut jobs: JoinSet<()> = JoinSet::new(); | 110 | let mut jobs: JoinSet<()> = JoinSet::new(); |
| 140 | - // Hashed once at startup. Without it, or with auto_update off, updates stay disabled. | ||
| 141 | let exe = if self.config.auto_update { | 111 | let exe = if self.config.auto_update { |
| 142 | match update::locate_self() { | 112 | match update::locate_self() { |
| 143 | Ok(found) => Some(found), | 113 | Ok(found) => Some(found), |
| @@ -161,16 +131,13 @@ impl Runner { | |||
| 161 | auto_update = updates.enabled(), | 131 | auto_update = updates.enabled(), |
| 162 | "runner started" | 132 | "runner started" |
| 163 | ); | 133 | ); |
| 164 | - // Parent of every job's token, so a `now` restart can cancel them all at once. | ||
| 165 | let jobs_cancel = shutdown.child_token(); | 134 | let jobs_cancel = shutdown.child_token(); |
| 166 | - // Ships the runner's own log to the forge until the loop has ended. See `selflog`. | ||
| 167 | let ship_stop = CancellationToken::new(); | 135 | let ship_stop = CancellationToken::new(); |
| 168 | let shipper = tokio::spawn(selflog::ship( | 136 | let shipper = tokio::spawn(selflog::ship( |
| 169 | self.client.clone(), | 137 | self.client.clone(), |
| 170 | self.config.runner_secret.clone(), | 138 | self.config.runner_secret.clone(), |
| 171 | ship_stop.clone(), | 139 | ship_stop.clone(), |
| 172 | )); | 140 | )); |
| 173 | - // Host samples for the graphs, stopped with the same token. Jobs in use = slots taken. | ||
| 174 | let limiter = self.limiter.clone(); | 141 | let limiter = self.limiter.clone(); |
| 175 | let metrics_shipper = tokio::spawn(metrics::ship( | 142 | let metrics_shipper = tokio::spawn(metrics::ship( |
| 176 | self.client.clone(), | 143 | self.client.clone(), |
| @@ -182,7 +149,6 @@ impl Runner { | |||
| 182 | }, | 149 | }, |
| 183 | ship_stop.clone(), | 150 | ship_stop.clone(), |
| 184 | )); | 151 | )); |
| 185 | - // The reason the claim loop last logged for not claiming, see `not_claiming`. | ||
| 186 | let mut blocked: Option<String> = None; | 152 | let mut blocked: Option<String> = None; |
| 187 | let end = loop { | 153 | let end = loop { |
| 188 | match restart::decide( | 154 | match restart::decide( |
| @@ -208,11 +174,7 @@ impl Runner { | |||
| 208 | ); | 174 | ); |
| 209 | tokio::select! { | 175 | tokio::select! { |
| 210 | _ = shutdown.cancelled() => break RunEnd::Stopped, | 176 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 211 | - Some(joined) = jobs.join_next() => { | 177 | + Some(joined) = jobs.join_next() => log_joined(joined), |
| 212 | - if let Err(e) = joined { | ||
| 213 | - tracing::error!(error = %e, "job task panicked"); | ||
| 214 | - } | ||
| 215 | - } | ||
| 216 | () = self.restart.changed() => {} | 178 | () = self.restart.changed() => {} |
| 217 | } | 179 | } |
| 218 | continue; | 180 | continue; |
| @@ -222,18 +184,13 @@ impl Runner { | |||
| 222 | && let Some(sha) = updates.pending().map(str::to_owned) | 184 | && let Some(sha) = updates.pending().map(str::to_owned) |
| 223 | { | 185 | { |
| 224 | if !jobs.is_empty() { | 186 | if !jobs.is_empty() { |
| 225 | - // Claiming is paused until the running jobs finish. | ||
| 226 | not_claiming( | 187 | not_claiming( |
| 227 | &mut blocked, | 188 | &mut blocked, |
| 228 | "a new binary is pending, waiting for the running jobs".to_owned(), | 189 | "a new binary is pending, waiting for the running jobs".to_owned(), |
| 229 | ); | 190 | ); |
| 230 | tokio::select! { | 191 | tokio::select! { |
| 231 | _ = shutdown.cancelled() => break RunEnd::Stopped, | 192 | _ = shutdown.cancelled() => break RunEnd::Stopped, |
| 232 | - Some(joined) = jobs.join_next() => { | 193 | + Some(joined) = jobs.join_next() => log_joined(joined), |
| 233 | - if let Err(e) = joined { | ||
| 234 | - tracing::error!(error = %e, "job task panicked"); | ||
| 235 | - } | ||
| 236 | - } | ||
| 237 | } | 194 | } |
| 238 | continue; | 195 | continue; |
| 239 | } | 196 | } |
| @@ -257,8 +214,6 @@ impl Runner { | |||
| 257 | } | 214 | } |
| 258 | 215 | ||
| 259 | if let Some(pressure) = &self.pressure { | 216 | if let Some(pressure) = &self.pressure { |
| 260 | - // A parked job or a box under pressure means no new job. The controller wakes | ||
| 261 | - // this when that changes. | ||
| 262 | let gate = pressure.gate(); | 217 | let gate = pressure.gate(); |
| 263 | if !gate.open() { | 218 | if !gate.open() { |
| 264 | let hot = if gate.hot { ", box under pressure" } else { "" }; | 219 | let hot = if gate.hot { ", box under pressure" } else { "" }; |
| @@ -273,7 +228,6 @@ impl Runner { | |||
| 273 | () = pressure.wait_open() => {} | 228 | () = pressure.wait_open() => {} |
| 274 | } | 229 | } |
| 275 | } | 230 | } |
| 276 | - // Every slot taken: the loop waits below for a job to finish. A free slot ends the block. | ||
| 277 | if self.limiter.free_slots() == 0 { | 231 | if self.limiter.free_slots() == 0 { |
| 278 | let limit = self.limiter.current(); | 232 | let limit = self.limiter.current(); |
| 279 | not_claiming(&mut blocked, format!("{limit} of {limit} jobs running")); | 233 | not_claiming(&mut blocked, format!("{limit} of {limit} jobs running")); |
| @@ -298,7 +252,6 @@ impl Runner { | |||
| 298 | &self.config.labels, | 252 | &self.config.labels, |
| 299 | Some(self.limiter.current()), | 253 | Some(self.limiter.current()), |
| 300 | Some(MemoryClaim { | 254 | Some(MemoryClaim { |
| 301 | - // Real room in the box when memory control is on, else what is promised. | ||
| 302 | free: self | 255 | free: self |
| 303 | .pressure | 256 | .pressure |
| 304 | .as_ref() | 257 | .as_ref() |
| @@ -311,7 +264,6 @@ impl Runner { | |||
| 311 | }; | 264 | }; |
| 312 | match claimed { | 265 | match claimed { |
| 313 | Ok(reply) => { | 266 | Ok(reply) => { |
| 314 | - // No header means no override: back to the runner.toml value. | ||
| 315 | self.limiter.apply_logged(reply.concurrency); | 267 | self.limiter.apply_logged(reply.concurrency); |
| 316 | self.memory.apply_logged( | 268 | self.memory.apply_logged( |
| 317 | reply.memory_budget.as_deref(), | 269 | reply.memory_budget.as_deref(), |
| @@ -340,7 +292,6 @@ impl Runner { | |||
| 340 | ); | 292 | ); |
| 341 | let runner = self.clone(); | 293 | let runner = self.clone(); |
| 342 | let cancel = jobs_cancel.child_token(); | 294 | let cancel = jobs_cancel.child_token(); |
| 343 | - // Reserved before the next claim, so that claim sees less free memory. | ||
| 344 | let reservation = self.memory.reserve(job.memory_bytes); | 295 | let reservation = self.memory.reserve(job.memory_bytes); |
| 345 | jobs.spawn(async move { | 296 | jobs.spawn(async move { |
| 346 | let _permit = permit; | 297 | let _permit = permit; |
| @@ -361,27 +312,20 @@ impl Runner { | |||
| 361 | } | 312 | } |
| 362 | } | 313 | } |
| 363 | while let Some(joined) = jobs.try_join_next() { | 314 | while let Some(joined) = jobs.try_join_next() { |
| 364 | - if let Err(e) = joined { | 315 | + log_joined(joined); |
| 365 | - tracing::error!(error = %e, "job task panicked"); | ||
| 366 | - } | ||
| 367 | } | 316 | } |
| 368 | }; | 317 | }; |
| 369 | while let Some(joined) = jobs.join_next().await { | 318 | while let Some(joined) = jobs.join_next().await { |
| 370 | - if let Err(e) = joined { | 319 | + log_joined(joined); |
| 371 | - tracing::error!(error = %e, "job task panicked"); | ||
| 372 | - } | ||
| 373 | } | 320 | } |
| 374 | tracing::info!("runner stopped"); | 321 | tracing::info!("runner stopped"); |
| 375 | - // The last lines go out too, but a dead forge must not hold up the exit. | ||
| 376 | ship_stop.cancel(); | 322 | ship_stop.cancel(); |
| 377 | let _ = tokio::time::timeout(LOG_FLUSH, shipper).await; | 323 | let _ = tokio::time::timeout(LOG_FLUSH, shipper).await; |
| 378 | let _ = tokio::time::timeout(LOG_FLUSH, metrics_shipper).await; | 324 | let _ = tokio::time::timeout(LOG_FLUSH, metrics_shipper).await; |
| 379 | end | 325 | end |
| 380 | } | 326 | } |
| 381 | 327 | ||
| 382 | - /// Runs one claimed job end to end and reports its result. Returns the final outcome. | ||
| 383 | pub async fn process(&self, job: JobAssignment, shutdown: CancellationToken) -> Outcome { | 328 | pub async fn process(&self, job: JobAssignment, shutdown: CancellationToken) -> Outcome { |
| 384 | - // Mask the job's secret values and its own token, both raw and base64 (done by Masker). | ||
| 385 | let mut secret_values: Vec<String> = job.secrets.values().cloned().collect(); | 329 | let mut secret_values: Vec<String> = job.secrets.values().cloned().collect(); |
| 386 | secret_values.push(job.job_token.clone()); | 330 | secret_values.push(job.job_token.clone()); |
| 387 | let masker = Masker::new(secret_values); | 331 | let masker = Masker::new(secret_values); |
| @@ -426,7 +370,6 @@ impl Runner { | |||
| 426 | let flag = timed_out.clone(); | 370 | let flag = timed_out.clone(); |
| 427 | let pause = registration.as_ref().map(|r| r.pause_clock()); | 371 | let pause = registration.as_ref().map(|r| r.pause_clock()); |
| 428 | tokio::spawn(async move { | 372 | tokio::spawn(async move { |
| 429 | - // Time spent frozen does not count, so the deadline moves out by the pauses. | ||
| 430 | let started = Instant::now(); | 373 | let started = Instant::now(); |
| 431 | loop { | 374 | loop { |
| 432 | let paused = pause.as_ref().map(|p| p.paused()).unwrap_or_default(); | 375 | let paused = pause.as_ref().map(|p| p.paused()).unwrap_or_default(); |
| @@ -474,16 +417,12 @@ impl Runner { | |||
| 474 | }, | 417 | }, |
| 475 | }; | 418 | }; |
| 476 | 419 | ||
| 477 | - // The memory controller killed this job to run it again later: give it back to the queue | ||
| 478 | - // without a result. | ||
| 479 | if registration.as_ref().is_some_and(|r| r.requeued()) { | 420 | if registration.as_ref().is_some_and(|r| r.requeued()) { |
| 480 | heartbeat.abort(); | 421 | heartbeat.abort(); |
| 481 | timer.abort(); | 422 | timer.abort(); |
| 482 | drop(registration); | 423 | drop(registration); |
| 483 | drop(tx); | 424 | drop(tx); |
| 484 | let _ = pump.await; | 425 | let _ = pump.await; |
| 485 | - // The workspace is named after the job, so it goes before the job is handed back: a | ||
| 486 | - // free slot here may claim it again at once and build in the same folder. | ||
| 487 | if let Some(dir) = workspace_dir.take() | 426 | if let Some(dir) = workspace_dir.take() |
| 488 | && let Err(e) = workspace::cleanup(&dir).await | 427 | && let Err(e) = workspace::cleanup(&dir).await |
| 489 | { | 428 | { |
| @@ -509,7 +448,6 @@ impl Runner { | |||
| 509 | return Outcome::Cancelled; | 448 | return Outcome::Cancelled; |
| 510 | } | 449 | } |
| 511 | 450 | ||
| 512 | - // Artifacts only come from a successful run. | ||
| 513 | let upload_error = match workspace_dir.as_deref() { | 451 | let upload_error = match workspace_dir.as_deref() { |
| 514 | Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { | 452 | Some(dir) if result.outcome == Outcome::Success && !job.artifacts.is_empty() => { |
| 515 | self.upload_artifacts(&job, dir).await.err() | 453 | self.upload_artifacts(&job, dir).await.err() |
| @@ -526,7 +464,6 @@ impl Runner { | |||
| 526 | 464 | ||
| 527 | heartbeat.abort(); | 465 | heartbeat.abort(); |
| 528 | timer.abort(); | 466 | timer.abort(); |
| 529 | - // The log sender it holds must go before the log shipper can finish. | ||
| 530 | drop(registration); | 467 | drop(registration); |
| 531 | if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { | 468 | if timed_out.load(Ordering::SeqCst) && result.outcome == Outcome::Cancelled { |
| 532 | result = ExecResult { | 469 | result = ExecResult { |
| @@ -540,7 +477,6 @@ impl Runner { | |||
| 540 | result.message = Some("cancelled because an admin restarted the runner".to_owned()); | 477 | result.message = Some("cancelled because an admin restarted the runner".to_owned()); |
| 541 | } | 478 | } |
| 542 | 479 | ||
| 543 | - // The save decides on the final outcome. It also clears the job's scratch dirs. | ||
| 544 | if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { | 480 | if let (Some(cache), Some(dir)) = (&self.cache, workspace_dir.as_deref()) { |
| 545 | for line in cache.save(&job, result.outcome, dir).await { | 481 | for line in cache.save(&job, result.outcome, dir).await { |
| 546 | send_line(&tx, line).await; | 482 | send_line(&tx, line).await; |
| @@ -600,7 +536,6 @@ impl Runner { | |||
| 600 | cancel.cancel(); | 536 | cancel.cancel(); |
| 601 | return; | 537 | return; |
| 602 | } | 538 | } |
| 603 | - // A runner at its limit does not claim, so the heartbeat carries changes too. | ||
| 604 | Ok(beat) => { | 539 | Ok(beat) => { |
| 605 | limiter.apply_logged(beat.concurrency); | 540 | limiter.apply_logged(beat.concurrency); |
| 606 | restart.observe(beat.restart); | 541 | restart.observe(beat.restart); |
| @@ -611,7 +546,6 @@ impl Runner { | |||
| 611 | }) | 546 | }) |
| 612 | } | 547 | } |
| 613 | 548 | ||
| 614 | - /// Collects the job's artifacts and uploads them. The error is a message for the job record. | ||
| 615 | async fn upload_artifacts( | 549 | async fn upload_artifacts( |
| 616 | &self, | 550 | &self, |
| 617 | job: &JobAssignment, | 551 | job: &JobAssignment, |
| @@ -637,8 +571,6 @@ impl Runner { | |||
| 637 | oom_killed: oom_kills.map(|_| true), | 571 | oom_killed: oom_kills.map(|_| true), |
| 638 | oom_kills, | 572 | oom_kills, |
| 639 | }; | 573 | }; |
| 640 | - // A forge that is down or restarting is waited for; a forge that refuses the result | ||
| 641 | - // (the job was reaped, cancelled or its token ended) is not asked again. | ||
| 642 | let started = Instant::now(); | 574 | let started = Instant::now(); |
| 643 | let mut attempt = 0u32; | 575 | let mut attempt = 0u32; |
| 644 | loop { | 576 | loop { |
| @@ -652,7 +584,7 @@ impl Runner { | |||
| 652 | ClientError::Status { status, .. } => status.is_server_error(), | 584 | ClientError::Status { status, .. } => status.is_server_error(), |
| 653 | _ => false, | 585 | _ => false, |
| 654 | }; | 586 | }; |
| 655 | - if (!away && attempt >= 3) || started.elapsed() >= FINISH_PATIENCE { | 587 | + if !away || started.elapsed() >= FINISH_PATIENCE { |
| 656 | break; | 588 | break; |
| 657 | } | 589 | } |
| 658 | let wait = Duration::from_secs((2 * u64::from(attempt)).min(15)); | 590 | let wait = Duration::from_secs((2 * u64::from(attempt)).min(15)); |
| @@ -667,8 +599,6 @@ impl Runner { | |||
| 667 | } | 599 | } |
| 668 | } | 600 | } |
| 669 | 601 | ||
| 670 | -/// Logs why the claim loop is not claiming, at info level, but only when the reason differs from | ||
| 671 | -/// the one logged last. `last` is cleared once the loop passes the checks and has a free slot. | ||
| 672 | fn not_claiming(last: &mut Option<String>, reason: String) { | 602 | fn not_claiming(last: &mut Option<String>, reason: String) { |
| 673 | if last.as_deref() != Some(reason.as_str()) { | 603 | if last.as_deref() != Some(reason.as_str()) { |
| 674 | tracing::info!("not claiming: {reason}"); | 604 | tracing::info!("not claiming: {reason}"); |
| @@ -676,6 +606,12 @@ fn not_claiming(last: &mut Option<String>, reason: String) { | |||
| 676 | } | 606 | } |
| 677 | } | 607 | } |
| 678 | 608 | ||
| 609 | +fn log_joined(joined: Result<(), tokio::task::JoinError>) { | ||
| 610 | + if let Err(e) = joined { | ||
| 611 | + tracing::error!(error = %e, "job task panicked"); | ||
| 612 | + } | ||
| 613 | +} | ||
| 614 | + | ||
| 679 | async fn send_line(tx: &mpsc::Sender<Vec<u8>>, line: String) { | 615 | async fn send_line(tx: &mpsc::Sender<Vec<u8>>, line: String) { |
| 680 | let mut bytes = line.into_bytes(); | 616 | let mut bytes = line.into_bytes(); |
| 681 | bytes.push(b'\n'); | 617 | bytes.push(b'\n'); |
crates/forge-runner/src/sandbox/exec.rsmodified+5 -7
| @@ -53,11 +53,9 @@ fn exec_process(spec: &Spec) -> Result<(), ExecutorError> { | |||
| 53 | .iter() | 53 | .iter() |
| 54 | .map(|s| CString::new(s.as_bytes()).map_err(|_| ExecutorError::InvalidArg)) | 54 | .map(|s| CString::new(s.as_bytes()).map_err(|_| ExecutorError::InvalidArg)) |
| 55 | .collect::<Result<Vec<CString>, ExecutorError>>()?; | 55 | .collect::<Result<Vec<CString>, ExecutorError>>()?; |
| 56 | - match unistd::execvp(&path, &argv) { | 56 | + let err = unistd::execvp(&path, &argv).unwrap_err(); |
| 57 | - Ok(never) => match never {}, | 57 | + Err(ExecutorError::Other(format!( |
| 58 | - Err(err) => Err(ExecutorError::Other(format!( | 58 | + "cannot exec {}: {err}", |
| 59 | - "cannot exec {}: {err}", | 59 | + path.to_string_lossy() |
| 60 | - path.to_string_lossy() | 60 | + ))) |
| 61 | - ))), | ||
| 62 | - } | ||
| 63 | } | 61 | } |
crates/forge-runner/src/sandbox/helper.rsmodified+0 -22
| @@ -58,7 +58,6 @@ const HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopba | |||
| 58 | 58 | ||
| 59 | /// Entry point for `forge-runner __sandbox`. Returns the process exit code. | 59 | /// Entry point for `forge-runner __sandbox`. Returns the process exit code. |
| 60 | pub fn helper_main() -> i32 { | 60 | pub fn helper_main() -> i32 { |
| 61 | - // libcontainer logs through tracing. Its logs appear only when the operator sets RUST_LOG. | ||
| 62 | if std::env::var_os("RUST_LOG").is_some() { | 61 | if std::env::var_os("RUST_LOG").is_some() { |
| 63 | let _ = tracing_subscriber::fmt() | 62 | let _ = tracing_subscriber::fmt() |
| 64 | .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) | 63 | .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) |
| @@ -113,7 +112,6 @@ fn run() -> Result<i32, SandboxError> { | |||
| 113 | prepare_dirs(&layout)?; | 112 | prepare_dirs(&layout)?; |
| 114 | write_etc_files(&layout)?; | 113 | write_etc_files(&layout)?; |
| 115 | 114 | ||
| 116 | - // The job's own network, when it asked for one and pasta is installed. See `net`. | ||
| 117 | let pasta_pid = net::pid_file(&layout.job_dir); | 115 | let pasta_pid = net::pid_file(&layout.job_dir); |
| 118 | let pending_net = match (&req.pasta, req.network) { | 116 | let pending_net = match (&req.pasta, req.network) { |
| 119 | (Some(pasta), true) => Some(net::prepare(pasta, &pasta_pid)?), | 117 | (Some(pasta), true) => Some(net::prepare(pasta, &pasta_pid)?), |
| @@ -125,12 +123,8 @@ fn run() -> Result<i32, SandboxError> { | |||
| 125 | None => Ok(()), | 123 | None => Ok(()), |
| 126 | } | 124 | } |
| 127 | .and_then(|()| mount_rootfs(&req, &layout)) | 125 | .and_then(|()| mount_rootfs(&req, &layout)) |
| 128 | - // Clean up on failure too: the state dir holds the job env. | ||
| 129 | .and_then(|rootfs| run_job(&req, &layout, &rootfs, &signals)); | 126 | .and_then(|rootfs| run_job(&req, &layout, &rootfs, &signals)); |
| 130 | net::stop_pasta(&pasta_pid); | 127 | net::stop_pasta(&pasta_pid); |
| 131 | - // The container is gone, so nothing writes to the workspace now. In subuid mode the job may | ||
| 132 | - // have left files owned by subordinate ids, which the runner can't remove, so they go back | ||
| 133 | - // to the runner. | ||
| 134 | if req.idmap.is_subuid() { | 128 | if req.idmap.is_subuid() { |
| 135 | reown_workspace(&req.workspace); | 129 | reown_workspace(&req.workspace); |
| 136 | } | 130 | } |
| @@ -212,7 +206,6 @@ fn install_signal_handlers() -> Result<Signals, SandboxError> { | |||
| 212 | let setup = |e: io::Error| SandboxError::Setup(format!("cannot install signal handler: {e}")); | 206 | let setup = |e: io::Error| SandboxError::Setup(format!("cannot install signal handler: {e}")); |
| 213 | let (wake, write_end) = | 207 | let (wake, write_end) = |
| 214 | UnixStream::pair().map_err(SandboxError::io("cannot create the signal pipe"))?; | 208 | UnixStream::pair().map_err(SandboxError::io("cannot create the signal pipe"))?; |
| 215 | - // Both ends are non-blocking. A signal handler must never block on a full pipe. | ||
| 216 | wake.set_nonblocking(true) | 209 | wake.set_nonblocking(true) |
| 217 | .map_err(SandboxError::io("cannot configure the signal pipe"))?; | 210 | .map_err(SandboxError::io("cannot configure the signal pipe"))?; |
| 218 | write_end | 211 | write_end |
| @@ -261,7 +254,6 @@ fn write_etc_files(layout: &Layout) -> Result<(), SandboxError> { | |||
| 261 | let hostname = layout.etc.join("hostname"); | 254 | let hostname = layout.etc.join("hostname"); |
| 262 | fs::write(&hostname, format!("{HOSTNAME}\n")) | 255 | fs::write(&hostname, format!("{HOSTNAME}\n")) |
| 263 | .map_err(SandboxError::io("cannot write hostname"))?; | 256 | .map_err(SandboxError::io("cannot write hostname"))?; |
| 264 | - // Only bind mounted when the job has its own network (see `spec`). | ||
| 265 | let resolv = layout.etc.join("resolv.conf"); | 257 | let resolv = layout.etc.join("resolv.conf"); |
| 266 | fs::write(&resolv, format!("nameserver {}\n", net::DNS_ADDR)) | 258 | fs::write(&resolv, format!("nameserver {}\n", net::DNS_ADDR)) |
| 267 | .map_err(SandboxError::io("cannot write resolv.conf"))?; | 259 | .map_err(SandboxError::io("cannot write resolv.conf"))?; |
| @@ -288,8 +280,6 @@ fn mount_rootfs(req: &SandboxRequest, layout: &Layout) -> Result<PathBuf, Sandbo | |||
| 288 | } | 280 | } |
| 289 | 281 | ||
| 290 | fn mount_overlay(lower: &Path, layout: &Layout) -> Result<(), SandboxError> { | 282 | fn mount_overlay(lower: &Path, layout: &Layout) -> Result<(), SandboxError> { |
| 291 | - // Overlay options are comma separated, and the colon separates lower dirs, so paths | ||
| 292 | - // containing either can't be expressed. | ||
| 293 | for p in [lower, &layout.upper, &layout.work] { | 283 | for p in [lower, &layout.upper, &layout.work] { |
| 294 | let s = p.to_string_lossy(); | 284 | let s = p.to_string_lossy(); |
| 295 | if s.contains(',') || s.contains(':') { | 285 | if s.contains(',') || s.contains(':') { |
| @@ -377,13 +367,11 @@ fn run_job( | |||
| 377 | /// `/sys/fs/cgroup` joined with it. | 367 | /// `/sys/fs/cgroup` joined with it. |
| 378 | pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, SandboxError> { | 368 | pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, SandboxError> { |
| 379 | let base = job_cgroup_base()?; | 369 | let base = job_cgroup_base()?; |
| 380 | - // With the runner's box in place (see `crate::pressure`), jobs live inside it. | ||
| 381 | let base = if box_ready(&base) { | 370 | let base = if box_ready(&base) { |
| 382 | base.join(BOX_NAME) | 371 | base.join(BOX_NAME) |
| 383 | } else { | 372 | } else { |
| 384 | base | 373 | base |
| 385 | }; | 374 | }; |
| 386 | - // The helper's pid keeps the name unique even if two helpers share a job id. | ||
| 387 | Ok(base.join(format!("forge-job-{job_id}-{helper_pid}"))) | 375 | Ok(base.join(format!("forge-job-{job_id}-{helper_pid}"))) |
| 388 | } | 376 | } |
| 389 | 377 | ||
| @@ -445,8 +433,6 @@ fn launch_and_wait( | |||
| 445 | spec: &Spec, | 433 | spec: &Spec, |
| 446 | signals: &Signals, | 434 | signals: &Signals, |
| 447 | ) -> Result<i32, SandboxError> { | 435 | ) -> Result<i32, SandboxError> { |
| 448 | - // Start each attempt with an empty state dir, so a failed attempt leaves no state behind. | ||
| 449 | - // The dir may not exist yet on the first attempt, so a failure here is not an error. | ||
| 450 | let _ = fs::remove_dir_all(&layout.state); | 436 | let _ = fs::remove_dir_all(&layout.state); |
| 451 | fs::create_dir_all(&layout.state).map_err(SandboxError::io("cannot create state dir"))?; | 437 | fs::create_dir_all(&layout.state).map_err(SandboxError::io("cannot create state dir"))?; |
| 452 | fs::set_permissions(&layout.state, fs::Permissions::from_mode(0o700)) | 438 | fs::set_permissions(&layout.state, fs::Permissions::from_mode(0o700)) |
| @@ -454,8 +440,6 @@ fn launch_and_wait( | |||
| 454 | 440 | ||
| 455 | write_bundle(layout, spec)?; | 441 | write_bundle(layout, spec)?; |
| 456 | let built = build_container(layout, id); | 442 | let built = build_container(layout, id); |
| 457 | - // libcontainer has read the bundle config during build, and the env it holds is now in | ||
| 458 | - // state. Delete the bundle copy now. | ||
| 459 | let _ = fs::remove_file(layout.bundle.join("config.json")); | 443 | let _ = fs::remove_file(layout.bundle.join("config.json")); |
| 460 | let mut container = match built { | 444 | let mut container = match built { |
| 461 | Ok(c) => c, | 445 | Ok(c) => c, |
| @@ -508,7 +492,6 @@ fn build_container(layout: &Layout, id: &str) -> Result<Container, String> { | |||
| 508 | let devnull = fs::File::open("/dev/null").map_err(io_err)?; | 492 | let devnull = fs::File::open("/dev/null").map_err(io_err)?; |
| 509 | let stdout = io::stdout().as_fd().try_clone_to_owned().map_err(io_err)?; | 493 | let stdout = io::stdout().as_fd().try_clone_to_owned().map_err(io_err)?; |
| 510 | let stderr = io::stderr().as_fd().try_clone_to_owned().map_err(io_err)?; | 494 | let stderr = io::stderr().as_fd().try_clone_to_owned().map_err(io_err)?; |
| 511 | - // The seccomp BPF is compiled here, before libcontainer forks. The executor only installs it. | ||
| 512 | let filter = build_filter().map_err(|e| e.to_string())?; | 495 | let filter = build_filter().map_err(|e| e.to_string())?; |
| 513 | let builder = ContainerBuilder::new(id.to_owned(), SyscallType::default()) | 496 | let builder = ContainerBuilder::new(id.to_owned(), SyscallType::default()) |
| 514 | .validate_id() | 497 | .validate_id() |
| @@ -531,7 +514,6 @@ fn start_container(container: &mut Container) -> Result<Pid, SandboxError> { | |||
| 531 | container | 514 | container |
| 532 | .start() | 515 | .start() |
| 533 | .map_err(|e| SandboxError::Setup(format!("container: cannot start: {e}")))?; | 516 | .map_err(|e| SandboxError::Setup(format!("container: cannot start: {e}")))?; |
| 534 | - // libcontainer has its own nix, so its Pid is a different type. The raw value is the same. | ||
| 535 | container | 517 | container |
| 536 | .pid() | 518 | .pid() |
| 537 | .map(|pid| Pid::from_raw(pid.as_raw())) | 519 | .map(|pid| Pid::from_raw(pid.as_raw())) |
| @@ -566,8 +548,6 @@ fn wait_for_init( | |||
| 566 | } | 548 | } |
| 567 | match waitpid(pid, Some(WaitPidFlag::WNOHANG)) { | 549 | match waitpid(pid, Some(WaitPidFlag::WNOHANG)) { |
| 568 | Ok(WaitStatus::StillAlive) => { | 550 | Ok(WaitStatus::StillAlive) => { |
| 569 | - // A signal that arrived since the checks above has already written to the pipe, | ||
| 570 | - // so this returns at once and nothing is missed. | ||
| 571 | if let Err(e) = wait_for_signal(&signals.wake) { | 551 | if let Err(e) = wait_for_signal(&signals.wake) { |
| 572 | let _ = kill_container(container); | 552 | let _ = kill_container(container); |
| 573 | delete_container(container); | 553 | delete_container(container); |
| @@ -601,7 +581,6 @@ fn wait_for_init( | |||
| 601 | fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> { | 581 | fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> { |
| 602 | let mut fds = [PollFd::new(wake.as_fd(), PollFlags::POLLIN)]; | 582 | let mut fds = [PollFd::new(wake.as_fd(), PollFlags::POLLIN)]; |
| 603 | match poll(&mut fds, PollTimeout::NONE) { | 583 | match poll(&mut fds, PollTimeout::NONE) { |
| 604 | - // EINTR means a handler ran, and it wrote to the pipe. The drain below picks that up. | ||
| 605 | Ok(_) | Err(Errno::EINTR) => {} | 584 | Ok(_) | Err(Errno::EINTR) => {} |
| 606 | Err(e) => return Err(e), | 585 | Err(e) => return Err(e), |
| 607 | } | 586 | } |
| @@ -611,7 +590,6 @@ fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> { | |||
| 611 | Ok(0) => return Ok(()), | 590 | Ok(0) => return Ok(()), |
| 612 | Ok(_) => {} | 591 | Ok(_) => {} |
| 613 | Err(e) if e.kind() == io::ErrorKind::Interrupted => {} | 592 | Err(e) if e.kind() == io::ErrorKind::Interrupted => {} |
| 614 | - // WouldBlock means the pipe is empty. Any other read error can't be acted on either. | ||
| 615 | Err(_) => return Ok(()), | 593 | Err(_) => return Ok(()), |
| 616 | } | 594 | } |
| 617 | } | 595 | } |
crates/forge-runner/src/sandbox/idmap.rsmodified+28 -33
| @@ -47,16 +47,19 @@ pub enum UsernsMode { | |||
| 47 | Subuid, | 47 | Subuid, |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] | ||
| 51 | +pub struct SubRange { | ||
| 52 | + pub uid_start: u32, | ||
| 53 | + pub gid_start: u32, | ||
| 54 | + pub count: u32, | ||
| 55 | +} | ||
| 56 | + | ||
| 50 | /// The id mapping a sandbox uses. The helper receives it as JSON. | 57 | /// The id mapping a sandbox uses. The helper receives it as JSON. |
| 51 | -/// | ||
| 52 | -/// `sub_uid` and `sub_gid` are `(start, count)` ranges on the host. Both are set in subuid mode. | ||
| 53 | -/// Both must have the same count, so container ids `1..=count` are valid for uids and gids. | ||
| 54 | #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] | 58 | #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] |
| 55 | pub struct IdMap { | 59 | pub struct IdMap { |
| 56 | pub uid: u32, | 60 | pub uid: u32, |
| 57 | pub gid: u32, | 61 | pub gid: u32, |
| 58 | - pub sub_uid: Option<(u32, u32)>, | 62 | + pub sub: Option<SubRange>, |
| 59 | - pub sub_gid: Option<(u32, u32)>, | ||
| 60 | } | 63 | } |
| 61 | 64 | ||
| 62 | /// Errors from resolving or entering an id mapping. | 65 | /// Errors from resolving or entering an id mapping. |
| @@ -79,8 +82,7 @@ impl IdMap { | |||
| 79 | Self { | 82 | Self { |
| 80 | uid: getuid().as_raw(), | 83 | uid: getuid().as_raw(), |
| 81 | gid: getgid().as_raw(), | 84 | gid: getgid().as_raw(), |
| 82 | - sub_uid: None, | 85 | + sub: None, |
| 83 | - sub_gid: None, | ||
| 84 | } | 86 | } |
| 85 | } | 87 | } |
| 86 | 88 | ||
| @@ -98,22 +100,19 @@ impl IdMap { | |||
| 98 | 100 | ||
| 99 | /// Whether the map has subordinate ranges. | 101 | /// Whether the map has subordinate ranges. |
| 100 | pub fn is_subuid(&self) -> bool { | 102 | pub fn is_subuid(&self) -> bool { |
| 101 | - self.sub_uid.is_some() && self.sub_gid.is_some() | 103 | + self.sub.is_some() |
| 102 | } | 104 | } |
| 103 | 105 | ||
| 104 | /// How many container ids are mapped, including container 0. `1 + n` in subuid mode. | 106 | /// How many container ids are mapped, including container 0. `1 + n` in subuid mode. |
| 105 | pub fn size(&self) -> u32 { | 107 | pub fn size(&self) -> u32 { |
| 106 | - match (self.sub_uid, self.sub_gid) { | 108 | + self.sub.map_or(1, |s| 1 + s.count) |
| 107 | - (Some((_, n_uid)), Some((_, n_gid))) => 1 + n_uid.min(n_gid), | ||
| 108 | - _ => 1, | ||
| 109 | - } | ||
| 110 | } | 109 | } |
| 111 | 110 | ||
| 112 | /// A short description for logs, for example `subuid 524288+65536`. | 111 | /// A short description for logs, for example `subuid 524288+65536`. |
| 113 | pub fn describe(&self) -> String { | 112 | pub fn describe(&self) -> String { |
| 114 | - match (self.sub_uid, self.sub_gid) { | 113 | + match self.sub { |
| 115 | - (Some((start, count)), Some(_)) => format!("subuid {start}+{count}"), | 114 | + Some(s) => format!("subuid {}+{}", s.uid_start, s.count), |
| 116 | - _ => format!("single uid {}", self.uid), | 115 | + None => format!("single uid {}", self.uid), |
| 117 | } | 116 | } |
| 118 | } | 117 | } |
| 119 | } | 118 | } |
| @@ -209,8 +208,11 @@ fn subuid_map() -> Result<IdMap, String> { | |||
| 209 | Ok(IdMap { | 208 | Ok(IdMap { |
| 210 | uid, | 209 | uid, |
| 211 | gid, | 210 | gid, |
| 212 | - sub_uid: Some((uid_start, count)), | 211 | + sub: Some(SubRange { |
| 213 | - sub_gid: Some((gid_start, count)), | 212 | + uid_start, |
| 213 | + gid_start, | ||
| 214 | + count, | ||
| 215 | + }), | ||
| 214 | }) | 216 | }) |
| 215 | } | 217 | } |
| 216 | 218 | ||
| @@ -235,12 +237,9 @@ fn find_tool(name: &str) -> Option<PathBuf> { | |||
| 235 | /// Must be called from a single-threaded process, because the unshare needs one. The caller is | 237 | /// Must be called from a single-threaded process, because the unshare needs one. The caller is |
| 236 | /// the sandbox helper, which has no other threads. | 238 | /// the sandbox helper, which has no other threads. |
| 237 | pub fn enter_mapped_userns(map: &IdMap) -> Result<(), IdMapError> { | 239 | pub fn enter_mapped_userns(map: &IdMap) -> Result<(), IdMapError> { |
| 238 | - match (map.sub_uid, map.sub_gid) { | 240 | + match map.sub { |
| 239 | - (Some((uid_start, count_uid)), Some((gid_start, count_gid))) => { | 241 | + Some(s) => enter_subuid(map, s.uid_start, s.gid_start, s.count)?, |
| 240 | - let count = count_uid.min(count_gid).min(MAX_SUBID_COUNT); | 242 | + None => enter_single(map)?, |
| 241 | - enter_subuid(map, uid_start, gid_start, count)?; | ||
| 242 | - } | ||
| 243 | - _ => enter_single(map)?, | ||
| 244 | } | 243 | } |
| 245 | mount( | 244 | mount( |
| 246 | None::<&str>, | 245 | None::<&str>, |
| @@ -614,8 +613,7 @@ mod tests { | |||
| 614 | let single = IdMap { | 613 | let single = IdMap { |
| 615 | uid: 1000, | 614 | uid: 1000, |
| 616 | gid: 1000, | 615 | gid: 1000, |
| 617 | - sub_uid: None, | 616 | + sub: None, |
| 618 | - sub_gid: None, | ||
| 619 | }; | 617 | }; |
| 620 | assert!(!single.is_subuid()); | 618 | assert!(!single.is_subuid()); |
| 621 | assert_eq!(single.size(), 1); | 619 | assert_eq!(single.size(), 1); |
| @@ -624,18 +622,15 @@ mod tests { | |||
| 624 | let sub = IdMap { | 622 | let sub = IdMap { |
| 625 | uid: 1000, | 623 | uid: 1000, |
| 626 | gid: 1000, | 624 | gid: 1000, |
| 627 | - sub_uid: Some((524288, 65536)), | 625 | + sub: Some(SubRange { |
| 628 | - sub_gid: Some((524288, 65536)), | 626 | + uid_start: 524288, |
| 627 | + gid_start: 524288, | ||
| 628 | + count: 65536, | ||
| 629 | + }), | ||
| 629 | }; | 630 | }; |
| 630 | assert!(sub.is_subuid()); | 631 | assert!(sub.is_subuid()); |
| 631 | assert_eq!(sub.size(), 65537); | 632 | assert_eq!(sub.size(), 65537); |
| 632 | assert_eq!(sub.describe(), "subuid 524288+65536"); | 633 | assert_eq!(sub.describe(), "subuid 524288+65536"); |
| 633 | - | ||
| 634 | - let uneven = IdMap { | ||
| 635 | - sub_gid: Some((600000, 10)), | ||
| 636 | - ..sub | ||
| 637 | - }; | ||
| 638 | - assert_eq!(uneven.size(), 11); | ||
| 639 | } | 634 | } |
| 640 | 635 | ||
| 641 | fn os(args: &[&str]) -> Vec<OsString> { | 636 | fn os(args: &[&str]) -> Vec<OsString> { |
crates/forge-runner/src/sandbox/spec.rsmodified+42 -88
| @@ -69,6 +69,11 @@ pub fn build_spec(req: &SandboxRequest, rootfs_mount: &Path) -> Result<Spec, San | |||
| 69 | "-c".to_owned(), | 69 | "-c".to_owned(), |
| 70 | req.run.clone(), | 70 | req.run.clone(), |
| 71 | ]; | 71 | ]; |
| 72 | + let active: HashSet<Capability> = if req.idmap.is_subuid() { | ||
| 73 | + SUBUID_CAPABILITIES.into_iter().collect() | ||
| 74 | + } else { | ||
| 75 | + HashSet::new() | ||
| 76 | + }; | ||
| 72 | let process = ProcessBuilder::default() | 77 | let process = ProcessBuilder::default() |
| 73 | .terminal(false) | 78 | .terminal(false) |
| 74 | .user( | 79 | .user( |
| @@ -81,7 +86,7 @@ pub fn build_spec(req: &SandboxRequest, rootfs_mount: &Path) -> Result<Spec, San | |||
| 81 | .args(args) | 86 | .args(args) |
| 82 | .env(env) | 87 | .env(env) |
| 83 | .cwd(PathBuf::from(WORKSPACE)) | 88 | .cwd(PathBuf::from(WORKSPACE)) |
| 84 | - .capabilities(job_capabilities(req)?) | 89 | + .capabilities(capabilities(active)?) |
| 85 | .rlimits(vec![ | 90 | .rlimits(vec![ |
| 86 | rlimit(PosixRlimitType::RlimitNproc, req.limits.pids.into())?, | 91 | rlimit(PosixRlimitType::RlimitNproc, req.limits.pids.into())?, |
| 87 | rlimit(PosixRlimitType::RlimitNofile, NOFILE_LIMIT)?, | 92 | rlimit(PosixRlimitType::RlimitNofile, NOFILE_LIMIT)?, |
| @@ -138,7 +143,6 @@ fn build_env(req: &SandboxRequest) -> Result<Vec<String>, SandboxError> { | |||
| 138 | 143 | ||
| 139 | fn check_nul(entry: &str) -> Result<(), SandboxError> { | 144 | fn check_nul(entry: &str) -> Result<(), SandboxError> { |
| 140 | if entry.contains('\0') { | 145 | if entry.contains('\0') { |
| 141 | - // The name is safe to show, the value is not. | ||
| 142 | let name = entry.split('=').next().unwrap_or_default(); | 146 | let name = entry.split('=').next().unwrap_or_default(); |
| 143 | return Err(SandboxError::Invalid(format!("env {name} contains NUL"))); | 147 | return Err(SandboxError::Invalid(format!("env {name} contains NUL"))); |
| 144 | } | 148 | } |
| @@ -164,38 +168,19 @@ const SUBUID_CAPABILITIES: [Capability; 13] = [ | |||
| 164 | Capability::Mknod, | 168 | Capability::Mknod, |
| 165 | ]; | 169 | ]; |
| 166 | 170 | ||
| 167 | -/// The job's capability sets. Single mode has none. Subuid mode has [`SUBUID_CAPABILITIES`] in | 171 | +fn capabilities( |
| 168 | -/// the bounding, effective and permitted sets. Inheritable and ambient stay empty, so an exec | 172 | + active: HashSet<Capability>, |
| 169 | -/// doesn't gain more. | ||
| 170 | -fn job_capabilities( | ||
| 171 | - req: &SandboxRequest, | ||
| 172 | ) -> Result<oci_spec::runtime::LinuxCapabilities, SandboxError> { | 173 | ) -> Result<oci_spec::runtime::LinuxCapabilities, SandboxError> { |
| 173 | - if !req.idmap.is_subuid() { | ||
| 174 | - return no_capabilities(); | ||
| 175 | - } | ||
| 176 | - let set: HashSet<Capability> = SUBUID_CAPABILITIES.into_iter().collect(); | ||
| 177 | LinuxCapabilitiesBuilder::default() | 174 | LinuxCapabilitiesBuilder::default() |
| 178 | - .bounding(set.clone()) | 175 | + .bounding(active.clone()) |
| 179 | - .effective(set.clone()) | 176 | + .effective(active.clone()) |
| 180 | - .permitted(set) | 177 | + .permitted(active) |
| 181 | .inheritable(HashSet::new()) | 178 | .inheritable(HashSet::new()) |
| 182 | .ambient(HashSet::new()) | 179 | .ambient(HashSet::new()) |
| 183 | .build() | 180 | .build() |
| 184 | .map_err(spec_err) | 181 | .map_err(spec_err) |
| 185 | } | 182 | } |
| 186 | 183 | ||
| 187 | -fn no_capabilities() -> Result<oci_spec::runtime::LinuxCapabilities, SandboxError> { | ||
| 188 | - let empty: HashSet<Capability> = HashSet::new(); | ||
| 189 | - LinuxCapabilitiesBuilder::default() | ||
| 190 | - .bounding(empty.clone()) | ||
| 191 | - .effective(empty.clone()) | ||
| 192 | - .inheritable(empty.clone()) | ||
| 193 | - .permitted(empty.clone()) | ||
| 194 | - .ambient(empty) | ||
| 195 | - .build() | ||
| 196 | - .map_err(spec_err) | ||
| 197 | -} | ||
| 198 | - | ||
| 199 | fn rlimit( | 184 | fn rlimit( |
| 200 | typ: PosixRlimitType, | 185 | typ: PosixRlimitType, |
| 201 | value: u64, | 186 | value: u64, |
| @@ -209,10 +194,6 @@ fn rlimit( | |||
| 209 | } | 194 | } |
| 210 | 195 | ||
| 211 | fn build_linux(req: &SandboxRequest) -> Result<oci_spec::runtime::Linux, SandboxError> { | 196 | fn build_linux(req: &SandboxRequest) -> Result<oci_spec::runtime::Linux, SandboxError> { |
| 212 | - // In subuid mode the job runs in the helper's own user namespace, which already maps the | ||
| 213 | - // runner's uid and the subordinate range. libcontainer writes only one id range for a new | ||
| 214 | - // user namespace, and the kernel refuses a multi-id root map written from the parent. So the | ||
| 215 | - // job can't get its own namespace with the full range, and it uses the helper's. | ||
| 216 | let subuid = req.idmap.is_subuid(); | 197 | let subuid = req.idmap.is_subuid(); |
| 217 | let mut namespaces = Vec::new(); | 198 | let mut namespaces = Vec::new(); |
| 218 | if !subuid { | 199 | if !subuid { |
| @@ -230,25 +211,10 @@ fn build_linux(req: &SandboxRequest) -> Result<oci_spec::runtime::Linux, Sandbox | |||
| 230 | } | 211 | } |
| 231 | let mut linux = LinuxBuilder::default().namespaces(namespaces); | 212 | let mut linux = LinuxBuilder::default().namespaces(namespaces); |
| 232 | if !subuid { | 213 | if !subuid { |
| 233 | - // Single mode: container root maps to the helper's root, which is the runner's uid. | ||
| 234 | - let uid_map = LinuxIdMappingBuilder::default() | ||
| 235 | - .container_id(0u32) | ||
| 236 | - .host_id(0u32) | ||
| 237 | - .size(1u32) | ||
| 238 | - .build() | ||
| 239 | - .map_err(spec_err)?; | ||
| 240 | - let gid_map = LinuxIdMappingBuilder::default() | ||
| 241 | - .container_id(0u32) | ||
| 242 | - .host_id(0u32) | ||
| 243 | - .size(1u32) | ||
| 244 | - .build() | ||
| 245 | - .map_err(spec_err)?; | ||
| 246 | linux = linux | 214 | linux = linux |
| 247 | - .uid_mappings(vec![uid_map]) | 215 | + .uid_mappings(vec![identity_mapping()?]) |
| 248 | - .gid_mappings(vec![gid_map]); | 216 | + .gid_mappings(vec![identity_mapping()?]); |
| 249 | } | 217 | } |
| 250 | - // No seccomp section: libcontainer's libseccomp support is off, so it would ignore one. The | ||
| 251 | - // profile is installed by `exec::FilteredExecutor` instead. | ||
| 252 | linux | 218 | linux |
| 253 | .resources(build_resources(&req.limits)?) | 219 | .resources(build_resources(&req.limits)?) |
| 254 | .masked_paths( | 220 | .masked_paths( |
| @@ -267,6 +233,15 @@ fn build_linux(req: &SandboxRequest) -> Result<oci_spec::runtime::Linux, Sandbox | |||
| 267 | .map_err(spec_err) | 233 | .map_err(spec_err) |
| 268 | } | 234 | } |
| 269 | 235 | ||
| 236 | +fn identity_mapping() -> Result<oci_spec::runtime::LinuxIdMapping, SandboxError> { | ||
| 237 | + LinuxIdMappingBuilder::default() | ||
| 238 | + .container_id(0u32) | ||
| 239 | + .host_id(0u32) | ||
| 240 | + .size(1u32) | ||
| 241 | + .build() | ||
| 242 | + .map_err(spec_err) | ||
| 243 | +} | ||
| 244 | + | ||
| 270 | fn ns(typ: LinuxNamespaceType) -> Result<oci_spec::runtime::LinuxNamespace, SandboxError> { | 245 | fn ns(typ: LinuxNamespaceType) -> Result<oci_spec::runtime::LinuxNamespace, SandboxError> { |
| 271 | LinuxNamespaceBuilder::default() | 246 | LinuxNamespaceBuilder::default() |
| 272 | .typ(typ) | 247 | .typ(typ) |
| @@ -282,8 +257,6 @@ fn build_resources(limits: &Limits) -> Result<oci_spec::runtime::LinuxResources, | |||
| 282 | .memory( | 257 | .memory( |
| 283 | LinuxMemoryBuilder::default() | 258 | LinuxMemoryBuilder::default() |
| 284 | .limit(memory) | 259 | .limit(memory) |
| 285 | - // Memory plus swap is memory plus the job's share of swap (0 unless the budget | ||
| 286 | - // counts swap): past both the job is OOM-killed inside its own cgroup. | ||
| 287 | .swap(memory.saturating_add(i64::try_from(limits.swap).unwrap_or(i64::MAX))) | 260 | .swap(memory.saturating_add(i64::try_from(limits.swap).unwrap_or(i64::MAX))) |
| 288 | .build() | 261 | .build() |
| 289 | .map_err(spec_err)?, | 262 | .map_err(spec_err)?, |
| @@ -330,7 +303,7 @@ pub fn parse_cpus(text: &str) -> Result<f64, SandboxError> { | |||
| 330 | .trim() | 303 | .trim() |
| 331 | .parse() | 304 | .parse() |
| 332 | .map_err(|_| SandboxError::Invalid(format!("bad cpus limit {text:?}")))?; | 305 | .map_err(|_| SandboxError::Invalid(format!("bad cpus limit {text:?}")))?; |
| 333 | - if !value.is_finite() || value <= 0.0 { | 306 | + if !value.is_finite() || value < 0.01 { |
| 334 | return Err(SandboxError::Invalid(format!("bad cpus limit {text:?}"))); | 307 | return Err(SandboxError::Invalid(format!("bad cpus limit {text:?}"))); |
| 335 | } | 308 | } |
| 336 | Ok(value) | 309 | Ok(value) |
| @@ -369,31 +342,18 @@ fn build_mounts(req: &SandboxRequest) -> Result<Vec<Mount>, SandboxError> { | |||
| 369 | mounts.push(mount(&host, "bind", &host, &["bind", "nosuid", "noexec"])?); | 342 | mounts.push(mount(&host, "bind", &host, &["bind", "nosuid", "noexec"])?); |
| 370 | } | 343 | } |
| 371 | if req.network { | 344 | if req.network { |
| 372 | - // A sysfs mount needs a network namespace owned by the user namespace, and the shared | ||
| 373 | - // host one is not. A read-only recursive bind of the host's /sys is the fallback. | ||
| 374 | mounts.push(mount( | 345 | mounts.push(mount( |
| 375 | "/sys", | 346 | "/sys", |
| 376 | "bind", | 347 | "bind", |
| 377 | "/sys", | 348 | "/sys", |
| 378 | &["rbind", "nosuid", "noexec", "nodev", "ro"], | 349 | &["rbind", "nosuid", "noexec", "nodev", "ro"], |
| 379 | )?); | 350 | )?); |
| 380 | - // An isolated network asks pasta's DNS forwarder; the host's resolver may be on its | 351 | + let resolv = if req.pasta.is_some() { |
| 381 | - // loopback, which the job cannot reach. | 352 | + req.job_dir.join("etc/resolv.conf") |
| 382 | - if req.pasta.is_some() { | ||
| 383 | - mounts.push(mount_path( | ||
| 384 | - "/etc/resolv.conf", | ||
| 385 | - "bind", | ||
| 386 | - &req.job_dir.join("etc/resolv.conf"), | ||
| 387 | - &["bind", "ro"], | ||
| 388 | - )?); | ||
| 389 | } else { | 353 | } else { |
| 390 | - mounts.push(mount( | 354 | + PathBuf::from("/etc/resolv.conf") |
| 391 | - "/etc/resolv.conf", | 355 | + }; |
| 392 | - "bind", | 356 | + mounts.push(mount("/etc/resolv.conf", "bind", resolv, &["bind", "ro"])?); |
| 393 | - "/etc/resolv.conf", | ||
| 394 | - &["bind", "ro"], | ||
| 395 | - )?); | ||
| 396 | - } | ||
| 397 | } else { | 357 | } else { |
| 398 | mounts.push(mount( | 358 | mounts.push(mount( |
| 399 | "/sys", | 359 | "/sys", |
| @@ -402,27 +362,25 @@ fn build_mounts(req: &SandboxRequest) -> Result<Vec<Mount>, SandboxError> { | |||
| 402 | &["nosuid", "noexec", "nodev", "ro"], | 362 | &["nosuid", "noexec", "nodev", "ro"], |
| 403 | )?); | 363 | )?); |
| 404 | } | 364 | } |
| 405 | - mounts.push(mount_path( | 365 | + mounts.push(mount( |
| 406 | WORKSPACE, | 366 | WORKSPACE, |
| 407 | "bind", | 367 | "bind", |
| 408 | &req.workspace, | 368 | &req.workspace, |
| 409 | &["rbind", "rw", "nosuid", "nodev"], | 369 | &["rbind", "rw", "nosuid", "nodev"], |
| 410 | )?); | 370 | )?); |
| 411 | - // /tmp is a directory in the job dir, on disk: a tmpfs would charge temp files to the job's | 371 | + mounts.push(mount( |
| 412 | - // memory limit, and a test suite that writes many temp repos would be killed for it. | ||
| 413 | - mounts.push(mount_path( | ||
| 414 | "/tmp", | 372 | "/tmp", |
| 415 | "bind", | 373 | "bind", |
| 416 | &req.job_dir.join("tmp"), | 374 | &req.job_dir.join("tmp"), |
| 417 | &["rbind", "rw", "nosuid", "nodev"], | 375 | &["rbind", "rw", "nosuid", "nodev"], |
| 418 | )?); | 376 | )?); |
| 419 | - mounts.push(mount_path( | 377 | + mounts.push(mount( |
| 420 | "/etc/hosts", | 378 | "/etc/hosts", |
| 421 | "bind", | 379 | "bind", |
| 422 | &req.job_dir.join("etc/hosts"), | 380 | &req.job_dir.join("etc/hosts"), |
| 423 | &["bind", "ro"], | 381 | &["bind", "ro"], |
| 424 | )?); | 382 | )?); |
| 425 | - mounts.push(mount_path( | 383 | + mounts.push(mount( |
| 426 | "/etc/hostname", | 384 | "/etc/hostname", |
| 427 | "bind", | 385 | "bind", |
| 428 | &req.job_dir.join("etc/hostname"), | 386 | &req.job_dir.join("etc/hostname"), |
| @@ -431,20 +389,16 @@ fn build_mounts(req: &SandboxRequest) -> Result<Vec<Mount>, SandboxError> { | |||
| 431 | Ok(mounts) | 389 | Ok(mounts) |
| 432 | } | 390 | } |
| 433 | 391 | ||
| 434 | -fn mount(dest: &str, typ: &str, source: &str, options: &[&str]) -> Result<Mount, SandboxError> { | 392 | +fn mount( |
| 435 | - mount_path(dest, typ, Path::new(source), options) | ||
| 436 | -} | ||
| 437 | - | ||
| 438 | -fn mount_path( | ||
| 439 | dest: &str, | 393 | dest: &str, |
| 440 | typ: &str, | 394 | typ: &str, |
| 441 | - source: &Path, | 395 | + source: impl AsRef<Path>, |
| 442 | options: &[&str], | 396 | options: &[&str], |
| 443 | ) -> Result<Mount, SandboxError> { | 397 | ) -> Result<Mount, SandboxError> { |
| 444 | MountBuilder::default() | 398 | MountBuilder::default() |
| 445 | .destination(PathBuf::from(dest)) | 399 | .destination(PathBuf::from(dest)) |
| 446 | .typ(typ) | 400 | .typ(typ) |
| 447 | - .source(source) | 401 | + .source(source.as_ref()) |
| 448 | .options(options.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>()) | 402 | .options(options.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>()) |
| 449 | .build() | 403 | .build() |
| 450 | .map_err(spec_err) | 404 | .map_err(spec_err) |
| @@ -457,7 +411,7 @@ fn spec_err(e: impl std::fmt::Display) -> SandboxError { | |||
| 457 | #[cfg(test)] | 411 | #[cfg(test)] |
| 458 | mod tests { | 412 | mod tests { |
| 459 | use super::*; | 413 | use super::*; |
| 460 | - use crate::sandbox::idmap::IdMap; | 414 | + use crate::sandbox::idmap::{IdMap, SubRange}; |
| 461 | use std::collections::HashSet; | 415 | use std::collections::HashSet; |
| 462 | 416 | ||
| 463 | fn request(network: bool) -> SandboxRequest { | 417 | fn request(network: bool) -> SandboxRequest { |
| @@ -527,8 +481,11 @@ mod tests { | |||
| 527 | req.idmap = IdMap { | 481 | req.idmap = IdMap { |
| 528 | uid: 1000, | 482 | uid: 1000, |
| 529 | gid: 1000, | 483 | gid: 1000, |
| 530 | - sub_uid: Some((524_288, 65_536)), | 484 | + sub: Some(SubRange { |
| 531 | - sub_gid: Some((524_288, 65_536)), | 485 | + uid_start: 524_288, |
| 486 | + gid_start: 524_288, | ||
| 487 | + count: 65_536, | ||
| 488 | + }), | ||
| 532 | }; | 489 | }; |
| 533 | let spec = build_spec(&req, Path::new("/rootfs")).expect("spec"); | 490 | let spec = build_spec(&req, Path::new("/rootfs")).expect("spec"); |
| 534 | assert!(!namespace_types(&spec).contains("user")); | 491 | assert!(!namespace_types(&spec).contains("user")); |
| @@ -578,8 +535,6 @@ mod tests { | |||
| 578 | 535 | ||
| 579 | #[test] | 536 | #[test] |
| 580 | fn spec_has_no_seccomp_section() { | 537 | fn spec_has_no_seccomp_section() { |
| 581 | - // The seccomp filter is built in `seccomp.rs` and installed by `exec.rs`. A seccomp | ||
| 582 | - // section here would be dead config that libcontainer ignores. | ||
| 583 | let spec = spec_for(false); | 538 | let spec = spec_for(false); |
| 584 | assert!(spec.linux().as_ref().expect("linux").seccomp().is_none()); | 539 | assert!(spec.linux().as_ref().expect("linux").seccomp().is_none()); |
| 585 | } | 540 | } |
| @@ -648,7 +603,6 @@ mod tests { | |||
| 648 | res.memory().as_ref().and_then(|m| m.limit()), | 603 | res.memory().as_ref().and_then(|m| m.limit()), |
| 649 | Some(2 * 1024 * 1024 * 1024) | 604 | Some(2 * 1024 * 1024 * 1024) |
| 650 | ); | 605 | ); |
| 651 | - // Memory plus swap equals memory, so the cgroup gets memory.swap.max = 0. | ||
| 652 | assert_eq!( | 606 | assert_eq!( |
| 653 | res.memory().as_ref().and_then(|m| m.swap()), | 607 | res.memory().as_ref().and_then(|m| m.swap()), |
| 654 | Some(2 * 1024 * 1024 * 1024) | 608 | Some(2 * 1024 * 1024 * 1024) |
| @@ -691,7 +645,6 @@ mod tests { | |||
| 691 | assert!(pos("LANG=C.UTF-8") < pos("HOME=/root")); | 645 | assert!(pos("LANG=C.UTF-8") < pos("HOME=/root")); |
| 692 | assert!(pos("FORGE_CI=true") < pos("BUILD=1")); | 646 | assert!(pos("FORGE_CI=true") < pos("BUILD=1")); |
| 693 | assert!(pos("BUILD=1") < pos("TOKEN=s3cret-token")); | 647 | assert!(pos("BUILD=1") < pos("TOKEN=s3cret-token")); |
| 694 | - // The image PATH is used, so no default PATH is added. | ||
| 695 | assert_eq!(env.iter().filter(|e| e.starts_with("PATH=")).count(), 1); | 648 | assert_eq!(env.iter().filter(|e| e.starts_with("PATH=")).count(), 1); |
| 696 | } | 649 | } |
| 697 | 650 | ||
| @@ -758,6 +711,7 @@ mod tests { | |||
| 758 | fn parse_cpus_rejects_zero_and_junk() { | 711 | fn parse_cpus_rejects_zero_and_junk() { |
| 759 | assert_eq!(parse_cpus("2").expect("2"), 2.0); | 712 | assert_eq!(parse_cpus("2").expect("2"), 2.0); |
| 760 | assert!(parse_cpus("0").is_err()); | 713 | assert!(parse_cpus("0").is_err()); |
| 714 | + assert!(parse_cpus("0.005").is_err()); | ||
| 761 | assert!(parse_cpus("nan").is_err()); | 715 | assert!(parse_cpus("nan").is_err()); |
| 762 | assert!(parse_cpus("two").is_err()); | 716 | assert!(parse_cpus("two").is_err()); |
| 763 | } | 717 | } |
crates/forge-runner/src/selflog.rsmodified+6 -25
| @@ -8,7 +8,7 @@ use std::fmt::{Debug, Write as _}; | |||
| 8 | use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; | 8 | use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; |
| 9 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; | 9 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 10 | 10 | ||
| 11 | -use forge_ci::proto::{RunnerLogBatch, RunnerLogLine}; | 11 | +use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, RunnerLogLine, truncate_text}; |
| 12 | use reqwest::StatusCode; | 12 | use reqwest::StatusCode; |
| 13 | use tokio_util::sync::CancellationToken; | 13 | use tokio_util::sync::CancellationToken; |
| 14 | use tracing::field::{Field, Visit}; | 14 | use tracing::field::{Field, Visit}; |
| @@ -20,8 +20,6 @@ use crate::client::{ClientError, ForgeClient}; | |||
| 20 | 20 | ||
| 21 | /// Most lines the ring holds. The oldest are dropped first. | 21 | /// Most lines the ring holds. The oldest are dropped first. |
| 22 | pub const CAPACITY: usize = 2000; | 22 | pub const CAPACITY: usize = 2000; |
| 23 | -/// Longest text kept for one line, in bytes. Longer text is cut on a character boundary. | ||
| 24 | -pub const MAX_TEXT: usize = 4096; | ||
| 25 | /// Most lines in one batch. | 23 | /// Most lines in one batch. |
| 26 | pub const BATCH: usize = 500; | 24 | pub const BATCH: usize = 500; |
| 27 | /// Time between two shipping attempts. | 25 | /// Time between two shipping attempts. |
| @@ -79,11 +77,6 @@ impl Ring { | |||
| 79 | state.next += 1; | 77 | state.next += 1; |
| 80 | } | 78 | } |
| 81 | 79 | ||
| 82 | - /// The number the next line will get. | ||
| 83 | - pub fn end(&self) -> u64 { | ||
| 84 | - self.lock().next | ||
| 85 | - } | ||
| 86 | - | ||
| 87 | /// Up to `max` lines from number `from` on. Lines already dropped are skipped, so the first | 80 | /// Up to `max` lines from number `from` on. Lines already dropped are skipped, so the first |
| 88 | /// returned number is `from` or later. The number is returned with the lines. | 81 | /// returned number is `from` or later. The number is returned with the lines. |
| 89 | pub fn batch(&self, from: u64, max: usize) -> (u64, Vec<RunnerLogLine>) { | 82 | pub fn batch(&self, from: u64, max: usize) -> (u64, Vec<RunnerLogLine>) { |
| @@ -121,7 +114,7 @@ impl<S: Subscriber> Layer<S> for SelfLog { | |||
| 121 | self.ring.push(RunnerLogLine { | 114 | self.ring.push(RunnerLogLine { |
| 122 | at_ms: now_ms(), | 115 | at_ms: now_ms(), |
| 123 | level: level_name(*meta.level()).to_owned(), | 116 | level: level_name(*meta.level()).to_owned(), |
| 124 | - text: truncate(text.finish()), | 117 | + text: truncate_text(&text.finish(), RUNNER_LOG_MAX_TEXT).to_owned(), |
| 125 | }); | 118 | }); |
| 126 | } | 119 | } |
| 127 | } | 120 | } |
| @@ -178,18 +171,6 @@ pub(crate) fn now_ms() -> i64 { | |||
| 178 | .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) | 171 | .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)) |
| 179 | } | 172 | } |
| 180 | 173 | ||
| 181 | -/// Cuts `text` to at most [`MAX_TEXT`] bytes, on a character boundary. | ||
| 182 | -fn truncate(mut text: String) -> String { | ||
| 183 | - if text.len() > MAX_TEXT { | ||
| 184 | - let mut end = MAX_TEXT; | ||
| 185 | - while !text.is_char_boundary(end) { | ||
| 186 | - end -= 1; | ||
| 187 | - } | ||
| 188 | - text.truncate(end); | ||
| 189 | - } | ||
| 190 | - text | ||
| 191 | -} | ||
| 192 | - | ||
| 193 | /// Posts the lines the forge has not seen yet, every two seconds, under the boot id of this | 174 | /// Posts the lines the forge has not seen yet, every two seconds, under the boot id of this |
| 194 | /// process. Failures are logged at debug level and retried on the next tick. When `stop` is | 175 | /// process. Failures are logged at debug level and retried on the next tick. When `stop` is |
| 195 | /// cancelled, the lines still held are sent before returning, so the caller may bound this with a | 176 | /// cancelled, the lines still held are sent before returning, so the caller may bound this with a |
| @@ -257,7 +238,7 @@ mod tests { | |||
| 257 | for i in 0..5 { | 238 | for i in 0..5 { |
| 258 | ring.push(line(&i.to_string())); | 239 | ring.push(line(&i.to_string())); |
| 259 | } | 240 | } |
| 260 | - assert_eq!(ring.end(), 5); | 241 | + assert_eq!(ring.batch(5, 10).0, 5); |
| 261 | let (first, lines) = ring.batch(0, 10); | 242 | let (first, lines) = ring.batch(0, 10); |
| 262 | assert_eq!(first, 2); | 243 | assert_eq!(first, 2); |
| 263 | let texts: Vec<_> = lines.iter().map(|l| l.text.as_str()).collect(); | 244 | let texts: Vec<_> = lines.iter().map(|l| l.text.as_str()).collect(); |
| @@ -280,9 +261,9 @@ mod tests { | |||
| 280 | 261 | ||
| 281 | #[test] | 262 | #[test] |
| 282 | fn long_text_is_cut_on_a_char_boundary() { | 263 | fn long_text_is_cut_on_a_char_boundary() { |
| 283 | - let text = "é".repeat(MAX_TEXT); | 264 | + let text = "é".repeat(RUNNER_LOG_MAX_TEXT); |
| 284 | - let cut = truncate(text); | 265 | + let cut = truncate_text(&text, RUNNER_LOG_MAX_TEXT); |
| 285 | - assert!(cut.len() <= MAX_TEXT); | 266 | + assert!(cut.len() <= RUNNER_LOG_MAX_TEXT); |
| 286 | assert!(cut.ends_with('é')); | 267 | assert!(cut.ends_with('é')); |
| 287 | } | 268 | } |
| 288 | } | 269 | } |
crates/forge-runner/src/update.rsmodified+2 -2
| @@ -15,8 +15,8 @@ use sha2::{Digest, Sha256}; | |||
| 15 | 15 | ||
| 16 | use crate::client::{ClientError, ForgeClient}; | 16 | use crate::client::{ClientError, ForgeClient}; |
| 17 | 17 | ||
| 18 | -/// The exit code after a successful swap. systemd restarts the runner on any non-zero code. | 18 | +pub use forge_ci::proto::RESTART_EXIT_CODE; |
| 19 | -pub const RESTART_EXIT_CODE: u8 = 75; | 19 | + |
| 20 | /// How long the new binary gets to answer `--version`. | 20 | /// How long the new binary gets to answer `--version`. |
| 21 | const SMOKE_TIMEOUT: Duration = Duration::from_secs(10); | 21 | const SMOKE_TIMEOUT: Duration = Duration::from_secs(10); |
| 22 | /// The temp file, next to the running binary, that the download goes to. | 22 | /// The temp file, next to the running binary, that the download goes to. |
crates/forge-runner/src/workspace.rsmodified+1 -14
| @@ -46,18 +46,6 @@ pub fn validate_commit(commit: &str) -> Result<(), WorkspaceError> { | |||
| 46 | } | 46 | } |
| 47 | } | 47 | } |
| 48 | 48 | ||
| 49 | -/// Whether `file://` clone URLs are accepted. Only test builds may fetch from a local path. | ||
| 50 | -#[cfg(any(test, feature = "test-host-executor"))] | ||
| 51 | -const fn local_file_urls_allowed() -> bool { | ||
| 52 | - true | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -/// Whether `file://` clone URLs are accepted. Production builds never accept them. | ||
| 56 | -#[cfg(not(any(test, feature = "test-host-executor")))] | ||
| 57 | -const fn local_file_urls_allowed() -> bool { | ||
| 58 | - false | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | /// Clone URLs must be a URL with a plain scheme. A leading `-` would be read as a git option. | 49 | /// Clone URLs must be a URL with a plain scheme. A leading `-` would be read as a git option. |
| 62 | /// | 50 | /// |
| 63 | /// Production accepts `https://` only, plus `http://` when the forge itself is `http://`. | 51 | /// Production accepts `https://` only, plus `http://` when the forge itself is `http://`. |
| @@ -65,7 +53,7 @@ const fn local_file_urls_allowed() -> bool { | |||
| 65 | pub fn validate_clone_url(url: &str, forge_url: &str) -> Result<(), WorkspaceError> { | 53 | pub fn validate_clone_url(url: &str, forge_url: &str) -> Result<(), WorkspaceError> { |
| 66 | let allowed = url.starts_with("https://") | 54 | let allowed = url.starts_with("https://") |
| 67 | || (url.starts_with("http://") && forge_url.starts_with("http://")) | 55 | || (url.starts_with("http://") && forge_url.starts_with("http://")) |
| 68 | - || (url.starts_with("file://") && local_file_urls_allowed()); | 56 | + || (url.starts_with("file://") && cfg!(any(test, feature = "test-host-executor"))); |
| 69 | if allowed && !url.contains(char::is_whitespace) { | 57 | if allowed && !url.contains(char::is_whitespace) { |
| 70 | Ok(()) | 58 | Ok(()) |
| 71 | } else { | 59 | } else { |
| @@ -242,7 +230,6 @@ mod tests { | |||
| 242 | fn file_urls_are_accepted_in_test_builds_only() { | 230 | fn file_urls_are_accepted_in_test_builds_only() { |
| 243 | // This test builds with cfg(test), so file:// is allowed here. Production builds refuse it. | 231 | // This test builds with cfg(test), so file:// is allowed here. Production builds refuse it. |
| 244 | assert!(validate_clone_url("file:///nonexistent/repo", "https://forge.example").is_ok()); | 232 | assert!(validate_clone_url("file:///nonexistent/repo", "https://forge.example").is_ok()); |
| 245 | - assert!(local_file_urls_allowed()); | ||
| 246 | } | 233 | } |
| 247 | 234 | ||
| 248 | #[tokio::test] | 235 | #[tokio::test] |
crates/forge-runner/tests/integration/flow.rsmodified+24 -30
| @@ -31,6 +31,7 @@ const RUNNER_SECRET: &str = "runner-secret-for-tests"; | |||
| 31 | const SECRET_VALUE: &str = "s3cr3t-value-echoed-by-job"; | 31 | const SECRET_VALUE: &str = "s3cr3t-value-echoed-by-job"; |
| 32 | const LOG_SIZE: &str = "X-Forge-Log-Size"; | 32 | const LOG_SIZE: &str = "X-Forge-Log-Size"; |
| 33 | const LOG_OFFSET: &str = "X-Forge-Log-Offset"; | 33 | const LOG_OFFSET: &str = "X-Forge-Log-Offset"; |
| 34 | +const JOB_ID: &str = "job-1"; | ||
| 34 | 35 | ||
| 35 | /// What the mock forge saw and what it should do. | 36 | /// What the mock forge saw and what it should do. |
| 36 | #[derive(Default)] | 37 | #[derive(Default)] |
| @@ -115,7 +116,7 @@ fn route( | |||
| 115 | let job = st.pending.remove(0); | 116 | let job = st.pending.remove(0); |
| 116 | Reply::json(&job) | 117 | Reply::json(&job) |
| 117 | } | 118 | } |
| 118 | - ("POST" | "PUT" | "GET", ["api", "v1", "ci", "jobs", job_id, rest @ ..]) => { | 119 | + ("POST" | "PUT", ["api", "v1", "ci", "jobs", job_id, rest @ ..]) => { |
| 119 | let Some(job) = st.by_id.get(*job_id) else { | 120 | let Some(job) = st.by_id.get(*job_id) else { |
| 120 | return Reply::empty(StatusCode::NOT_FOUND); | 121 | return Reply::empty(StatusCode::NOT_FOUND); |
| 121 | }; | 122 | }; |
| @@ -369,15 +370,14 @@ async fn start( | |||
| 369 | mut options: RunOptions, | 370 | mut options: RunOptions, |
| 370 | setup: impl FnOnce(&mut MockState), | 371 | setup: impl FnOnce(&mut MockState), |
| 371 | timeout: Option<Duration>, | 372 | timeout: Option<Duration>, |
| 372 | -) -> (Harness, String) { | 373 | +) -> Harness { |
| 373 | let dir = tempfile::tempdir().expect("tempdir"); | 374 | let dir = tempfile::tempdir().expect("tempdir"); |
| 374 | let commit = make_repo(dir.path()); | 375 | let commit = make_repo(dir.path()); |
| 375 | let clone_url = format!("file://{}", dir.path().join("repo").display()); | 376 | let clone_url = format!("file://{}", dir.path().join("repo").display()); |
| 376 | - let job_id = "job-1"; | ||
| 377 | let state: Shared = Arc::new(Mutex::new(MockState::default())); | 377 | let state: Shared = Arc::new(Mutex::new(MockState::default())); |
| 378 | { | 378 | { |
| 379 | let mut st = state.lock().expect("lock"); | 379 | let mut st = state.lock().expect("lock"); |
| 380 | - let j = job(job_id, &commit, &clone_url, run); | 380 | + let j = job(JOB_ID, &commit, &clone_url, run); |
| 381 | st.by_id.insert(j.job_id.clone(), j.clone()); | 381 | st.by_id.insert(j.job_id.clone(), j.clone()); |
| 382 | st.pending.push(j); | 382 | st.pending.push(j); |
| 383 | setup(&mut st); | 383 | setup(&mut st); |
| @@ -391,24 +391,20 @@ async fn start( | |||
| 391 | let stop = stop.clone(); | 391 | let stop = stop.clone(); |
| 392 | tokio::spawn(async move { runner.run(stop).await }) | 392 | tokio::spawn(async move { runner.run(stop).await }) |
| 393 | }; | 393 | }; |
| 394 | - ( | 394 | + Harness { |
| 395 | - Harness { | 395 | + state, |
| 396 | - state, | 396 | + stop, |
| 397 | - stop, | 397 | + runner_task, |
| 398 | - runner_task, | 398 | + _dir: dir, |
| 399 | - _dir: dir, | 399 | + } |
| 400 | - }, | ||
| 401 | - job_id.to_owned(), | ||
| 402 | - ) | ||
| 403 | } | 400 | } |
| 404 | 401 | ||
| 405 | -async fn finish_of(h: &Harness, job_id: &str) -> FinishRequest { | 402 | +async fn finish_of(h: &Harness) -> FinishRequest { |
| 406 | let state = h.state.clone(); | 403 | let state = h.state.clone(); |
| 407 | - let id = job_id.to_owned(); | ||
| 408 | wait_until("the job to finish", || { | 404 | wait_until("the job to finish", || { |
| 409 | state | 405 | state |
| 410 | .lock() | 406 | .lock() |
| 411 | - .map(|st| st.finished.contains_key(&id)) | 407 | + .map(|st| st.finished.contains_key(JOB_ID)) |
| 412 | .unwrap_or(false) | 408 | .unwrap_or(false) |
| 413 | }) | 409 | }) |
| 414 | .await; | 410 | .await; |
| @@ -416,7 +412,7 @@ async fn finish_of(h: &Harness, job_id: &str) -> FinishRequest { | |||
| 416 | .lock() | 412 | .lock() |
| 417 | .expect("lock") | 413 | .expect("lock") |
| 418 | .finished | 414 | .finished |
| 419 | - .get(job_id) | 415 | + .get(JOB_ID) |
| 420 | .cloned() | 416 | .cloned() |
| 421 | .expect("finish recorded") | 417 | .expect("finish recorded") |
| 422 | } | 418 | } |
| @@ -434,9 +430,9 @@ fn log_text(h: &Harness) -> String { | |||
| 434 | async fn full_flow_masks_secrets_and_uploads_artifacts() { | 430 | async fn full_flow_masks_secrets_and_uploads_artifacts() { |
| 435 | let run = "mkdir -p dist && echo built > dist/out.txt && echo \"token is $MY_TOKEN\" && \ | 431 | let run = "mkdir -p dist && echo built > dist/out.txt && echo \"token is $MY_TOKEN\" && \ |
| 436 | echo \"b64 $(printf %s \"$MY_TOKEN\" | base64)\" && echo \"env is $GREETING\""; | 432 | echo \"b64 $(printf %s \"$MY_TOKEN\" | base64)\" && echo \"env is $GREETING\""; |
| 437 | - let (h, job_id) = start(run, fast_options(), |_| {}, None).await; | 433 | + let h = start(run, fast_options(), |_| {}, None).await; |
| 438 | 434 | ||
| 439 | - let finish = finish_of(&h, &job_id).await; | 435 | + let finish = finish_of(&h).await; |
| 440 | assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); | 436 | assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); |
| 441 | assert_eq!(finish.exit_code, Some(0)); | 437 | assert_eq!(finish.exit_code, Some(0)); |
| 442 | 438 | ||
| @@ -470,18 +466,16 @@ fn base64_of(text: &str) -> String { | |||
| 470 | 466 | ||
| 471 | #[tokio::test] | 467 | #[tokio::test] |
| 472 | async fn heartbeat_cancel_stops_the_job() { | 468 | async fn heartbeat_cancel_stops_the_job() { |
| 473 | - let mut options = fast_options(); | 469 | + let h = start( |
| 474 | - options.heartbeat_every = Duration::from_millis(50); | ||
| 475 | - let (h, job_id) = start( | ||
| 476 | "echo start; sleep 60", | 470 | "echo start; sleep 60", |
| 477 | - options, | 471 | + fast_options(), |
| 478 | |st| st.cancel_from_heartbeat = Some(2), | 472 | |st| st.cancel_from_heartbeat = Some(2), |
| 479 | None, | 473 | None, |
| 480 | ) | 474 | ) |
| 481 | .await; | 475 | .await; |
| 482 | 476 | ||
| 483 | let started = Instant::now(); | 477 | let started = Instant::now(); |
| 484 | - let finish = finish_of(&h, &job_id).await; | 478 | + let finish = finish_of(&h).await; |
| 485 | assert_eq!(finish.outcome, Outcome::Cancelled, "{finish:?}"); | 479 | assert_eq!(finish.outcome, Outcome::Cancelled, "{finish:?}"); |
| 486 | assert!( | 480 | assert!( |
| 487 | started.elapsed() < Duration::from_secs(30), | 481 | started.elapsed() < Duration::from_secs(30), |
| @@ -492,7 +486,7 @@ async fn heartbeat_cancel_stops_the_job() { | |||
| 492 | 486 | ||
| 493 | #[tokio::test] | 487 | #[tokio::test] |
| 494 | async fn timeout_fails_the_job() { | 488 | async fn timeout_fails_the_job() { |
| 495 | - let (h, job_id) = start( | 489 | + let h = start( |
| 496 | "sleep 60", | 490 | "sleep 60", |
| 497 | fast_options(), | 491 | fast_options(), |
| 498 | |_| {}, | 492 | |_| {}, |
| @@ -500,7 +494,7 @@ async fn timeout_fails_the_job() { | |||
| 500 | ) | 494 | ) |
| 501 | .await; | 495 | .await; |
| 502 | 496 | ||
| 503 | - let finish = finish_of(&h, &job_id).await; | 497 | + let finish = finish_of(&h).await; |
| 504 | assert_eq!(finish.outcome, Outcome::Failure, "{finish:?}"); | 498 | assert_eq!(finish.outcome, Outcome::Failure, "{finish:?}"); |
| 505 | assert!( | 499 | assert!( |
| 506 | finish | 500 | finish |
| @@ -518,9 +512,9 @@ async fn log_offset_mismatch_resyncs_without_loss_or_duplicates() { | |||
| 518 | // Log POST #2 is applied by the forge for its first 3 bytes, then answered 409. The runner | 512 | // Log POST #2 is applied by the forge for its first 3 bytes, then answered 409. The runner |
| 519 | // must drop those 3 bytes and continue, so the stored log has every line exactly once. | 513 | // must drop those 3 bytes and continue, so the stored log has every line exactly once. |
| 520 | let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third"; | 514 | let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third"; |
| 521 | - let (h, job_id) = start(run, fast_options(), |st| st.ghost = Some((2, 3)), None).await; | 515 | + let h = start(run, fast_options(), |st| st.ghost = Some((2, 3)), None).await; |
| 522 | 516 | ||
| 523 | - let finish = finish_of(&h, &job_id).await; | 517 | + let finish = finish_of(&h).await; |
| 524 | assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); | 518 | assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); |
| 525 | 519 | ||
| 526 | let log = log_text(&h); | 520 | let log = log_text(&h); |
| @@ -540,9 +534,9 @@ async fn acknowledged_batch_the_forge_lost_is_resent_in_order() { | |||
| 540 | // Log POST #2 is acknowledged but never stored. The next POST gets 409 with the smaller size, | 534 | // Log POST #2 is acknowledged but never stored. The next POST gets 409 with the smaller size, |
| 541 | // and the runner must resend the lost bytes from its retained buffer, with no gap marker. | 535 | // and the runner must resend the lost bytes from its retained buffer, with no gap marker. |
| 542 | let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third"; | 536 | let run = "echo first; sleep 0.3; echo second; sleep 0.3; echo third"; |
| 543 | - let (h, job_id) = start(run, fast_options(), |st| st.drop_post = Some(2), None).await; | 537 | + let h = start(run, fast_options(), |st| st.drop_post = Some(2), None).await; |
| 544 | 538 | ||
| 545 | - let finish = finish_of(&h, &job_id).await; | 539 | + let finish = finish_of(&h).await; |
| 546 | assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); | 540 | assert_eq!(finish.outcome, Outcome::Success, "{finish:?}"); |
| 547 | 541 | ||
| 548 | let log = log_text(&h); | 542 | let log = log_text(&h); |
crates/forge-runner/tests/integration/idmap.rsmodified+6 -3
| @@ -5,7 +5,7 @@ use std::fs; | |||
| 5 | use std::path::Path; | 5 | use std::path::Path; |
| 6 | use std::process::{Command, Stdio}; | 6 | use std::process::{Command, Stdio}; |
| 7 | 7 | ||
| 8 | -use forge_runner::sandbox::idmap::{IdMap, UsernsMode, remove_tree}; | 8 | +use forge_runner::sandbox::idmap::{IdMap, SubRange, UsernsMode, remove_tree}; |
| 9 | 9 | ||
| 10 | #[test] | 10 | #[test] |
| 11 | fn remove_tree_deletes_files_owned_by_subordinate_ids() { | 11 | fn remove_tree_deletes_files_owned_by_subordinate_ids() { |
| @@ -47,8 +47,11 @@ fn remove_tree_treats_a_missing_path_as_done() { | |||
| 47 | let map = IdMap { | 47 | let map = IdMap { |
| 48 | uid: 1000, | 48 | uid: 1000, |
| 49 | gid: 1000, | 49 | gid: 1000, |
| 50 | - sub_uid: Some((524288, 65536)), | 50 | + sub: Some(SubRange { |
| 51 | - sub_gid: Some((524288, 65536)), | 51 | + uid_start: 524288, |
| 52 | + gid_start: 524288, | ||
| 53 | + count: 65536, | ||
| 54 | + }), | ||
| 52 | }; | 55 | }; |
| 53 | remove_tree(&map, &missing, exe).expect("subuid mode"); | 56 | remove_tree(&map, &missing, exe).expect("subuid mode"); |
| 54 | } | 57 | } |
crates/forge-runner/tests/integration/sandbox.rsmodified+4 -103
| @@ -1,93 +1,24 @@ | |||
| 1 | -//! Real sandbox tests. They run `forge-runner __sandbox` with a rootfs built here from the host's | ||
| 2 | -//! shell and a few utilities plus their shared libraries. Nothing is pulled from a registry, and | ||
| 3 | -//! there is no network access. The tests skip, with a message, when unprivileged user | ||
| 4 | -//! namespaces are unavailable. | ||
| 5 | - | ||
| 6 | use std::fs; | 1 | use std::fs; |
| 7 | use std::io::Write; | 2 | use std::io::Write; |
| 8 | -use std::path::{Path, PathBuf}; | 3 | +use std::path::Path; |
| 9 | use std::process::{Command, Output, Stdio}; | 4 | use std::process::{Command, Output, Stdio}; |
| 10 | use std::time::{Duration, Instant}; | 5 | use std::time::{Duration, Instant}; |
| 11 | 6 | ||
| 12 | use std::os::unix::fs::MetadataExt; | 7 | use std::os::unix::fs::MetadataExt; |
| 13 | 8 | ||
| 9 | +use forge_runner::check; | ||
| 14 | use forge_runner::config::Limits; | 10 | use forge_runner::config::Limits; |
| 15 | use forge_runner::sandbox::SandboxRequest; | 11 | use forge_runner::sandbox::SandboxRequest; |
| 16 | use forge_runner::sandbox::idmap::{IdMap, UsernsMode}; | 12 | use forge_runner::sandbox::idmap::{IdMap, UsernsMode}; |
| 17 | 13 | ||
| 18 | use crate::common::can_run; | 14 | use crate::common::can_run; |
| 19 | 15 | ||
| 20 | -/// Utilities copied into the test rootfs. `sh` is the job shell, and the rest are used by the | ||
| 21 | -/// test scripts. | ||
| 22 | const BINARIES: &[&str] = &[ | 16 | const BINARIES: &[&str] = &[ |
| 23 | "sh", "id", "cat", "grep", "touch", "sleep", "unshare", "chown", "stat", "mkdir", | 17 | "sh", "id", "cat", "grep", "touch", "sleep", "unshare", "chown", "stat", "mkdir", |
| 24 | ]; | 18 | ]; |
| 25 | 19 | ||
| 26 | -/// The shared libraries `ldd` reports for `binary`, as absolute host paths. | ||
| 27 | -fn shared_libs(binary: &Path) -> Vec<PathBuf> { | ||
| 28 | - let Ok(out) = Command::new("ldd").arg(binary).output() else { | ||
| 29 | - return Vec::new(); | ||
| 30 | - }; | ||
| 31 | - String::from_utf8_lossy(&out.stdout) | ||
| 32 | - .lines() | ||
| 33 | - .filter_map(|line| { | ||
| 34 | - let line = line.trim(); | ||
| 35 | - let path = match line.split_once(" => ") { | ||
| 36 | - Some((_, rest)) => rest.split(" (").next()?, | ||
| 37 | - None => line.split(" (").next()?, | ||
| 38 | - }; | ||
| 39 | - path.starts_with('/').then(|| PathBuf::from(path)) | ||
| 40 | - }) | ||
| 41 | - .collect() | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -fn copy_into(root: &Path, host: &Path) { | ||
| 45 | - let real = fs::canonicalize(host).expect("canonicalize host file"); | ||
| 46 | - let dest = root.join(host.strip_prefix("/").unwrap_or(host)); | ||
| 47 | - if let Some(parent) = dest.parent() { | ||
| 48 | - fs::create_dir_all(parent).expect("create dest dir"); | ||
| 49 | - } | ||
| 50 | - fs::copy(&real, &dest).expect("copy file into rootfs"); | ||
| 51 | -} | ||
| 52 | - | ||
| 53 | -/// Builds a tiny rootfs in `root`: the binaries in `/bin`, their shared libraries at the same | ||
| 54 | -/// absolute paths, and the empty mount points the spec needs. | ||
| 55 | fn build_rootfs(root: &Path) { | 20 | fn build_rootfs(root: &Path) { |
| 56 | - for dir in [ | 21 | + check::build_rootfs(root, BINARIES).expect("build rootfs"); |
| 57 | - "bin", | ||
| 58 | - "proc", | ||
| 59 | - "dev", | ||
| 60 | - "sys", | ||
| 61 | - "tmp", | ||
| 62 | - "workspace", | ||
| 63 | - "etc", | ||
| 64 | - "root", | ||
| 65 | - ] { | ||
| 66 | - fs::create_dir_all(root.join(dir)).expect("create rootfs dir"); | ||
| 67 | - } | ||
| 68 | - for name in ["null", "zero", "full", "random", "urandom"] { | ||
| 69 | - fs::write(root.join("dev").join(name), b"").expect("placeholder device"); | ||
| 70 | - } | ||
| 71 | - fs::write(root.join("etc/hosts"), b"").expect("placeholder hosts"); | ||
| 72 | - fs::write(root.join("etc/hostname"), b"").expect("placeholder hostname"); | ||
| 73 | - fs::write(root.join("etc/resolv.conf"), b"").expect("placeholder resolv.conf"); | ||
| 74 | - | ||
| 75 | - let mut libs: Vec<PathBuf> = Vec::new(); | ||
| 76 | - for name in BINARIES { | ||
| 77 | - let host = ["/usr/bin", "/bin"] | ||
| 78 | - .iter() | ||
| 79 | - .map(|dir| Path::new(dir).join(name)) | ||
| 80 | - .find(|p| p.exists()) | ||
| 81 | - .unwrap_or_else(|| panic!("{name} not found on this host")); | ||
| 82 | - let real = fs::canonicalize(&host).expect("canonicalize binary"); | ||
| 83 | - fs::copy(&real, root.join("bin").join(name)).expect("copy binary"); | ||
| 84 | - libs.extend(shared_libs(&real)); | ||
| 85 | - } | ||
| 86 | - libs.sort(); | ||
| 87 | - libs.dedup(); | ||
| 88 | - for lib in &libs { | ||
| 89 | - copy_into(root, lib); | ||
| 90 | - } | ||
| 91 | } | 22 | } |
| 92 | 23 | ||
| 93 | fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxRequest { | 24 | fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxRequest { |
| @@ -108,7 +39,6 @@ fn request(dir: &Path, rootfs: &Path, run: &str, network: bool) -> SandboxReques | |||
| 108 | } | 39 | } |
| 109 | } | 40 | } |
| 110 | 41 | ||
| 111 | -/// The subuid map, or `None` with a message when the host can't provide one. | ||
| 112 | fn subuid_map() -> Option<IdMap> { | 42 | fn subuid_map() -> Option<IdMap> { |
| 113 | match IdMap::resolve(UsernsMode::Subuid) { | 43 | match IdMap::resolve(UsernsMode::Subuid) { |
| 114 | Ok(map) if map.is_subuid() => Some(map), | 44 | Ok(map) if map.is_subuid() => Some(map), |
| @@ -120,7 +50,6 @@ fn subuid_map() -> Option<IdMap> { | |||
| 120 | } | 50 | } |
| 121 | } | 51 | } |
| 122 | 52 | ||
| 123 | -/// Spawns the helper and writes the request to its stdin. Returns the child, not yet waited on. | ||
| 124 | fn spawn_helper(req: &SandboxRequest) -> std::process::Child { | 53 | fn spawn_helper(req: &SandboxRequest) -> std::process::Child { |
| 125 | let mut child = Command::new(env!("CARGO_BIN_EXE_forge-runner")) | 54 | let mut child = Command::new(env!("CARGO_BIN_EXE_forge-runner")) |
| 126 | .arg("__sandbox") | 55 | .arg("__sandbox") |
| @@ -174,7 +103,6 @@ fn job_runs_as_root_with_no_capabilities() { | |||
| 174 | stdout.contains("NoNewPrivs:\t1"), | 103 | stdout.contains("NoNewPrivs:\t1"), |
| 175 | "no_new_privs off: {stdout}" | 104 | "no_new_privs off: {stdout}" |
| 176 | ); | 105 | ); |
| 177 | - // Seccomp mode 2 is a filter. The profile is installed by `sandbox::exec::FilteredExecutor`. | ||
| 178 | assert!( | 106 | assert!( |
| 179 | stdout.contains("Seccomp:\t2"), | 107 | stdout.contains("Seccomp:\t2"), |
| 180 | "seccomp filter not active: {stdout}" | 108 | "seccomp filter not active: {stdout}" |
| @@ -211,8 +139,6 @@ fn unshare_is_denied_inside_the_job() { | |||
| 211 | let dir = tempfile::tempdir().expect("tempdir"); | 139 | let dir = tempfile::tempdir().expect("tempdir"); |
| 212 | let rootfs = dir.path().join("rootfs"); | 140 | let rootfs = dir.path().join("rootfs"); |
| 213 | build_rootfs(&rootfs); | 141 | build_rootfs(&rootfs); |
| 214 | - // Creating a user namespace works on the host. The seccomp filter makes unshare(2) fail with | ||
| 215 | - // EPERM inside the job, so this must print "denied". | ||
| 216 | let run = "if unshare --user true 2>/dev/null; then echo allowed; else echo denied; fi"; | 142 | let run = "if unshare --user true 2>/dev/null; then echo allowed; else echo denied; fi"; |
| 217 | let out = run_helper(&request(dir.path(), &rootfs, run, false)); | 143 | let out = run_helper(&request(dir.path(), &rootfs, run, false)); |
| 218 | let stdout = stdout_of(&out); | 144 | let stdout = stdout_of(&out); |
| @@ -313,7 +239,6 @@ fn sigterm_kills_the_container_and_the_helper_exits() { | |||
| 313 | build_rootfs(&rootfs); | 239 | build_rootfs(&rootfs); |
| 314 | let req = request(dir.path(), &rootfs, "sleep 60", false); | 240 | let req = request(dir.path(), &rootfs, "sleep 60", false); |
| 315 | let child = spawn_helper(&req); | 241 | let child = spawn_helper(&req); |
| 316 | - // Give the container time to start, so that SIGTERM hits a running job. | ||
| 317 | std::thread::sleep(Duration::from_secs(2)); | 242 | std::thread::sleep(Duration::from_secs(2)); |
| 318 | let pid = nix::unistd::Pid::from_raw(i32::try_from(child.id()).expect("pid fits i32")); | 243 | let pid = nix::unistd::Pid::from_raw(i32::try_from(child.id()).expect("pid fits i32")); |
| 319 | nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGTERM).expect("send SIGTERM"); | 244 | nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGTERM).expect("send SIGTERM"); |
| @@ -347,8 +272,6 @@ fn rootfs_is_copied_when_the_overlay_cannot_be_mounted() { | |||
| 347 | return; | 272 | return; |
| 348 | } | 273 | } |
| 349 | let dir = tempfile::tempdir().expect("tempdir"); | 274 | let dir = tempfile::tempdir().expect("tempdir"); |
| 350 | - // A comma in a lower dir can't be written in overlay options, so the overlay mount fails | ||
| 351 | - // and the helper falls back to copying the rootfs. | ||
| 352 | let rootfs = dir.path().join("rootfs,copy"); | 275 | let rootfs = dir.path().join("rootfs,copy"); |
| 353 | build_rootfs(&rootfs); | 276 | build_rootfs(&rootfs); |
| 354 | let out = run_helper(&request( | 277 | let out = run_helper(&request( |
| @@ -368,7 +291,6 @@ fn rootfs_is_copied_when_the_overlay_cannot_be_mounted() { | |||
| 368 | assert!(!rootfs.join("etc/forge-marker").exists()); | 291 | assert!(!rootfs.join("etc/forge-marker").exists()); |
| 369 | } | 292 | } |
| 370 | 293 | ||
| 371 | -/// A request that runs under `map` (subuid mode when `map` has a range). | ||
| 372 | fn subuid_request(dir: &Path, rootfs: &Path, run: &str, map: &IdMap) -> SandboxRequest { | 294 | fn subuid_request(dir: &Path, rootfs: &Path, run: &str, map: &IdMap) -> SandboxRequest { |
| 373 | let mut req = request(dir, rootfs, run, false); | 295 | let mut req = request(dir, rootfs, run, false); |
| 374 | req.idmap = map.clone(); | 296 | req.idmap = map.clone(); |
| @@ -411,8 +333,6 @@ fn subuid_uid_and_gid_maps_have_one_plus_the_range() { | |||
| 411 | )); | 333 | )); |
| 412 | let stdout = stdout_of(&out); | 334 | let stdout = stdout_of(&out); |
| 413 | assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); | 335 | assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); |
| 414 | - // Each line is `inside outside count`. The job's root plus the subordinate range make the | ||
| 415 | - // map's size, which is `1 + n`, in one or two lines. Sum the counts for each map. | ||
| 416 | let sizes: Vec<u32> = stdout | 336 | let sizes: Vec<u32> = stdout |
| 417 | .lines() | 337 | .lines() |
| 418 | .filter_map(|l| l.split_whitespace().nth(2)?.parse().ok()) | 338 | .filter_map(|l| l.split_whitespace().nth(2)?.parse().ok()) |
| @@ -451,6 +371,7 @@ fn subuid_job_files_are_owned_by_the_runner_afterwards() { | |||
| 451 | ); | 371 | ); |
| 452 | let out = run_helper(&req); | 372 | let out = run_helper(&req); |
| 453 | assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); | 373 | assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); |
| 374 | + assert!(!req.job_dir.exists(), "the job dir was left behind"); | ||
| 454 | for path in ["a", "d", "d/x"] { | 375 | for path in ["a", "d", "d/x"] { |
| 455 | let path = req.workspace.join(path); | 376 | let path = req.workspace.join(path); |
| 456 | let meta = fs::symlink_metadata(&path).expect("stat workspace entry"); | 377 | let meta = fs::symlink_metadata(&path).expect("stat workspace entry"); |
| @@ -462,23 +383,3 @@ fn subuid_job_files_are_owned_by_the_runner_afterwards() { | |||
| 462 | ); | 383 | ); |
| 463 | } | 384 | } |
| 464 | } | 385 | } |
| 465 | - | ||
| 466 | -#[test] | ||
| 467 | -fn subuid_job_dir_is_removed_afterwards() { | ||
| 468 | - let Some(map) = subuid_map() else { return }; | ||
| 469 | - if !can_run() { | ||
| 470 | - return; | ||
| 471 | - } | ||
| 472 | - let dir = tempfile::tempdir().expect("tempdir"); | ||
| 473 | - let rootfs = dir.path().join("rootfs"); | ||
| 474 | - build_rootfs(&rootfs); | ||
| 475 | - let req = subuid_request( | ||
| 476 | - dir.path(), | ||
| 477 | - &rootfs, | ||
| 478 | - "touch /workspace/a && chown 1000:1000 /workspace/a", | ||
| 479 | - &map, | ||
| 480 | - ); | ||
| 481 | - let out = run_helper(&req); | ||
| 482 | - assert_eq!(out.status.code(), Some(0), "stderr: {}", stderr_of(&out)); | ||
| 483 | - assert!(!req.job_dir.exists(), "the job dir was left behind"); | ||
| 484 | -} | ||
crates/forge-runner/tests/integration/unpack_subuid.rsmodified+5 -21
| @@ -10,7 +10,7 @@ use std::path::Path; | |||
| 10 | use std::process::{Command, Output, Stdio}; | 10 | use std::process::{Command, Output, Stdio}; |
| 11 | 11 | ||
| 12 | use forge_runner::oci::UnpackStats; | 12 | use forge_runner::oci::UnpackStats; |
| 13 | -use forge_runner::sandbox::idmap::{IdMap, UsernsMode}; | 13 | +use forge_runner::sandbox::idmap::{IdMap, UsernsMode, remove_tree}; |
| 14 | 14 | ||
| 15 | /// The subuid map for this user, or None when the test should skip. | 15 | /// The subuid map for this user, or None when the test should skip. |
| 16 | fn subuid_map() -> Option<IdMap> { | 16 | fn subuid_map() -> Option<IdMap> { |
| @@ -86,30 +86,13 @@ fn run_unpack(map: &IdMap, rootfs: &Path, layer: &Path) -> Output { | |||
| 86 | child.wait_with_output().expect("wait for helper") | 86 | child.wait_with_output().expect("wait for helper") |
| 87 | } | 87 | } |
| 88 | 88 | ||
| 89 | -/// Removes a tree that holds subordinate-owned files, through `forge-runner __sandbox-rm`. | ||
| 90 | -fn remove_with_helper(map: &IdMap, path: &Path) { | ||
| 91 | - let mut child = Command::new(env!("CARGO_BIN_EXE_forge-runner")) | ||
| 92 | - .arg("__sandbox-rm") | ||
| 93 | - .arg(path) | ||
| 94 | - .stdin(Stdio::piped()) | ||
| 95 | - .spawn() | ||
| 96 | - .expect("spawn rm helper"); | ||
| 97 | - if let Some(mut stdin) = child.stdin.take() { | ||
| 98 | - let _ = stdin.write_all(&serde_json::to_vec(map).expect("serialize map")); | ||
| 99 | - } | ||
| 100 | - match child.wait() { | ||
| 101 | - Ok(status) if status.success() => {} | ||
| 102 | - other => eprintln!("warning: could not remove {}: {other:?}", path.display()), | ||
| 103 | - } | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | #[test] | 89 | #[test] |
| 107 | fn subuid_unpack_gives_files_their_subordinate_owner() { | 90 | fn subuid_unpack_gives_files_their_subordinate_owner() { |
| 108 | let Some(map) = subuid_map() else { | 91 | let Some(map) = subuid_map() else { |
| 109 | return; | 92 | return; |
| 110 | }; | 93 | }; |
| 111 | - let (uid_start, _) = map.sub_uid.expect("subuid map has a uid range"); | 94 | + let range = map.sub.expect("subuid map has a range"); |
| 112 | - let (gid_start, _) = map.sub_gid.expect("subuid map has a gid range"); | 95 | + let (uid_start, gid_start) = (range.uid_start, range.gid_start); |
| 113 | 96 | ||
| 114 | let dir = tempfile::tempdir().expect("tempdir"); | 97 | let dir = tempfile::tempdir().expect("tempdir"); |
| 115 | let layer = dir.path().join("layer.tar"); | 98 | let layer = dir.path().join("layer.tar"); |
| @@ -132,5 +115,6 @@ fn subuid_unpack_gives_files_their_subordinate_owner() { | |||
| 132 | assert_eq!(file.uid(), uid_start + 999, "host uid of srv/owned"); | 115 | assert_eq!(file.uid(), uid_start + 999, "host uid of srv/owned"); |
| 133 | assert_eq!(file.gid(), gid_start + 999, "host gid of srv/owned"); | 116 | assert_eq!(file.gid(), gid_start + 999, "host gid of srv/owned"); |
| 134 | 117 | ||
| 135 | - remove_with_helper(&map, &rootfs); | 118 | + remove_tree(&map, &rootfs, Path::new(env!("CARGO_BIN_EXE_forge-runner"))) |
| 119 | + .expect("remove rootfs"); | ||
| 136 | } | 120 | } |
crates/forge-web-account/src/pages/settings_live.rsmodified+3 -3
| @@ -66,9 +66,9 @@ pub async fn account_state( | |||
| 66 | let Some(user) = state.store.user_by_id(user_id).await? else { | 66 | let Some(user) = state.store.user_by_id(user_id).await? else { |
| 67 | return Ok((String::new(), String::new(), String::new())); | 67 | return Ok((String::new(), String::new(), String::new())); |
| 68 | }; | 68 | }; |
| 69 | - let theme = match crate::theme::resolve_preference(&user.theme) { | 69 | + let theme = match crate::theme::Theme::from_stored(&user.theme) { |
| 70 | - "auto" => "", | 70 | + crate::theme::Theme::Auto => "", |
| 71 | - theme => theme, | 71 | + theme => theme.as_str(), |
| 72 | }; | 72 | }; |
| 73 | let sidebar = if user.sidebar_side == "right" { | 73 | let sidebar = if user.sidebar_side == "right" { |
| 74 | "right" | 74 | "right" |
crates/forge-web-app/src/alerts.rsmodified+1 -1
| @@ -160,7 +160,7 @@ async fn deliver( | |||
| 160 | ); | 160 | ); |
| 161 | let outgoing = OutgoingMail { | 161 | let outgoing = OutgoingMail { |
| 162 | to: address.to_owned(), | 162 | to: address.to_owned(), |
| 163 | - subject: text::mail_subject(lang, &title), | 163 | + subject: text::mail_subject(&title), |
| 164 | body, | 164 | body, |
| 165 | message_id: None, | 165 | message_id: None, |
| 166 | in_reply_to: None, | 166 | in_reply_to: None, |
crates/forge-web-app/src/ci/runner_log.rsmodified+4 -18
| @@ -9,14 +9,12 @@ | |||
| 9 | use std::collections::{HashMap, VecDeque}; | 9 | use std::collections::{HashMap, VecDeque}; |
| 10 | use std::sync::{Mutex, MutexGuard}; | 10 | use std::sync::{Mutex, MutexGuard}; |
| 11 | 11 | ||
| 12 | -use forge_ci::proto::RunnerLogBatch; | 12 | +use forge_ci::proto::{RUNNER_LOG_MAX_TEXT, RunnerLogBatch, truncate_text}; |
| 13 | 13 | ||
| 14 | /// Most lines kept per runner. The oldest go first. | 14 | /// Most lines kept per runner. The oldest go first. |
| 15 | const MAX_LINES: usize = 2000; | 15 | const MAX_LINES: usize = 2000; |
| 16 | /// Most lines taken from one batch. The rest are left for the runner to resend. | 16 | /// Most lines taken from one batch. The rest are left for the runner to resend. |
| 17 | const MAX_BATCH_LINES: usize = 1000; | 17 | const MAX_BATCH_LINES: usize = 1000; |
| 18 | -/// Longest text kept per line, in bytes. Longer text is cut on a character boundary. | ||
| 19 | -const MAX_TEXT_BYTES: usize = 4096; | ||
| 20 | /// Longest boot id kept, in bytes. | 18 | /// Longest boot id kept, in bytes. |
| 21 | const MAX_BOOT_ID_BYTES: usize = 64; | 19 | const MAX_BOOT_ID_BYTES: usize = 64; |
| 22 | /// The levels a runner may send. Any other level is stored as `info`. | 20 | /// The levels a runner may send. Any other level is stored as `info`. |
| @@ -72,7 +70,7 @@ impl RunnerLogs { | |||
| 72 | push(entry, forge_line(format!("{missing} lines missing"))); | 70 | push(entry, forge_line(format!("{missing} lines missing"))); |
| 73 | } | 71 | } |
| 74 | for (i, line) in batch.lines.iter().take(MAX_BATCH_LINES).enumerate() { | 72 | for (i, line) in batch.lines.iter().take(MAX_BATCH_LINES).enumerate() { |
| 75 | - let seq = batch.first_seq + i as u64; | 73 | + let seq = batch.first_seq.saturating_add(i as u64); |
| 76 | if seq < entry.next_seq { | 74 | if seq < entry.next_seq { |
| 77 | continue; | 75 | continue; |
| 78 | } | 76 | } |
| @@ -81,13 +79,13 @@ impl RunnerLogs { | |||
| 81 | Line { | 79 | Line { |
| 82 | at_ms: line.at_ms, | 80 | at_ms: line.at_ms, |
| 83 | level: level_of(&line.level), | 81 | level: level_of(&line.level), |
| 84 | - text: cut(&line.text, MAX_TEXT_BYTES), | 82 | + text: truncate_text(&line.text, RUNNER_LOG_MAX_TEXT).to_owned(), |
| 85 | from_forge: false, | 83 | from_forge: false, |
| 86 | }, | 84 | }, |
| 87 | ); | 85 | ); |
| 88 | } | 86 | } |
| 89 | let taken = batch.lines.len().min(MAX_BATCH_LINES) as u64; | 87 | let taken = batch.lines.len().min(MAX_BATCH_LINES) as u64; |
| 90 | - entry.next_seq = entry.next_seq.max(batch.first_seq + taken); | 88 | + entry.next_seq = entry.next_seq.max(batch.first_seq.saturating_add(taken)); |
| 91 | entry.next_seq | 89 | entry.next_seq |
| 92 | } | 90 | } |
| 93 | 91 | ||
| @@ -160,18 +158,6 @@ fn level_of(level: &str) -> String { | |||
| 160 | } | 158 | } |
| 161 | } | 159 | } |
| 162 | 160 | ||
| 163 | -/// `text` cut to at most `max` bytes, on a character boundary. | ||
| 164 | -fn cut(text: &str, max: usize) -> String { | ||
| 165 | - if text.len() <= max { | ||
| 166 | - return text.to_owned(); | ||
| 167 | - } | ||
| 168 | - let mut end = max; | ||
| 169 | - while !text.is_char_boundary(end) { | ||
| 170 | - end -= 1; | ||
| 171 | - } | ||
| 172 | - text[..end].to_owned() | ||
| 173 | -} | ||
| 174 | - | ||
| 175 | #[cfg(test)] | 161 | #[cfg(test)] |
| 176 | mod tests { | 162 | mod tests { |
| 177 | use super::*; | 163 | use super::*; |
crates/forge-web-app/src/self_update.rsmodified+1 -2
| @@ -25,8 +25,7 @@ use topcoat::router::{Body, HeaderMap, StatusCode, response::Response}; | |||
| 25 | 25 | ||
| 26 | use crate::state::AppState; | 26 | use crate::state::AppState; |
| 27 | 27 | ||
| 28 | -/// Exit code after a swap. systemd `Restart=on-failure` restarts the unit on any non-zero exit. | 28 | +pub use forge_ci::proto::RESTART_EXIT_CODE; |
| 29 | -pub const RESTART_EXIT_CODE: u8 = 75; | ||
| 30 | /// Response header carrying the sha256 of the running binary, lowercase hex. | 29 | /// Response header carrying the sha256 of the running binary, lowercase hex. |
| 31 | pub const SHA_HEADER: &str = "Forge-Binary-Sha256"; | 30 | pub const SHA_HEADER: &str = "Forge-Binary-Sha256"; |
| 32 | /// Request header a runner sends with its `<arch>-<os>` target. | 31 | /// Request header a runner sends with its `<arch>-<os>` target. |
crates/forge-web-app/src/views/mod.rsmodified+12 -14
| @@ -48,6 +48,7 @@ use crate::i18n::s; | |||
| 48 | use crate::i18n::{self, Key, Lang, t}; | 48 | use crate::i18n::{self, Key, Lang, t}; |
| 49 | use crate::render::highlight::highlight_css; | 49 | use crate::render::highlight::highlight_css; |
| 50 | use crate::state::AppState; | 50 | use crate::state::AppState; |
| 51 | +use crate::theme::Theme; | ||
| 51 | 52 | ||
| 52 | /// Stylesheet URL. The version is a hash of the compiled CSS (build.rs), so a changed stylesheet | 53 | /// Stylesheet URL. The version is a hash of the compiled CSS (build.rs), so a changed stylesheet |
| 53 | /// gets a new URL and an unchanged one keeps its cache entry. | 54 | /// gets a new URL and an unchanged one keeps its cache entry. |
| @@ -632,16 +633,16 @@ pub async fn shell( | |||
| 632 | // The stored preference, "auto" included, drives the button: its icon, its label and the | 633 | // The stored preference, "auto" included, drives the button: its icon, its label and the |
| 633 | // value it posts (the next preference in the cycle auto, light, dark). | 634 | // value it posts (the next preference in the cycle auto, light, dark). |
| 634 | let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user)); | 635 | let theme_pref = crate::theme::preference(cx, viewer.map(|(user, _)| user)); |
| 635 | - let next_theme = crate::theme::next_preference(theme_pref); | 636 | + let next_theme = theme_pref.next().as_str(); |
| 636 | let theme_state = match theme_pref { | 637 | let theme_state = match theme_pref { |
| 637 | - "light" => mi::t(lang, MK::Light), | 638 | + Theme::Light => mi::t(lang, MK::Light), |
| 638 | - "dark" => mi::t(lang, MK::Dark), | 639 | + Theme::Dark => mi::t(lang, MK::Dark), |
| 639 | - _ => mi::t(lang, MK::MatchSystem), | 640 | + Theme::Auto => mi::t(lang, MK::MatchSystem), |
| 640 | }; | 641 | }; |
| 641 | - let theme_next = match next_theme { | 642 | + let theme_next = match theme_pref.next() { |
| 642 | - "light" => MK::SwitchToLight, | 643 | + Theme::Light => MK::SwitchToLight, |
| 643 | - "dark" => MK::SwitchToDark, | 644 | + Theme::Dark => MK::SwitchToDark, |
| 644 | - _ => MK::SwitchToMatchSystem, | 645 | + Theme::Auto => MK::SwitchToMatchSystem, |
| 645 | }; | 646 | }; |
| 646 | let switch_label = format!( | 647 | let switch_label = format!( |
| 647 | "{}: {}. {}", | 648 | "{}: {}. {}", |
| @@ -814,9 +815,9 @@ pub async fn shell( | |||
| 814 | } | 815 | } |
| 815 | <input type="hidden" name="theme" value=(next_theme)> | 816 | <input type="hidden" name="theme" value=(next_theme)> |
| 816 | <button type="submit" class="icon-btn" aria-label=(switch_label.as_str()) title=(switch_label.as_str())> | 817 | <button type="submit" class="icon-btn" aria-label=(switch_label.as_str()) title=(switch_label.as_str())> |
| 817 | - if theme_pref == "light" { | 818 | + if theme_pref == Theme::Light { |
| 818 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg> | 819 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg> |
| 819 | - } else if theme_pref == "dark" { | 820 | + } else if theme_pref == Theme::Dark { |
| 820 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/></svg> | 821 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/></svg> |
| 821 | } else { | 822 | } else { |
| 822 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/></svg> | 823 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/></svg> |
| @@ -1709,12 +1710,9 @@ pub fn url_path(path: &str) -> String { | |||
| 1709 | out | 1710 | out |
| 1710 | } | 1711 | } |
| 1711 | 1712 | ||
| 1712 | -/// Highlight classes, built once on first use. | ||
| 1713 | -static HIGHLIGHT_CSS: OnceLock<String> = OnceLock::new(); | ||
| 1714 | - | ||
| 1715 | /// The highlight classes, shared by the route and the page links (which hash them). | 1713 | /// The highlight classes, shared by the route and the page links (which hash them). |
| 1716 | pub fn highlight_css_text() -> &'static str { | 1714 | pub fn highlight_css_text() -> &'static str { |
| 1717 | - HIGHLIGHT_CSS.get_or_init(highlight_css).as_str() | 1715 | + highlight_css() |
| 1718 | } | 1716 | } |
| 1719 | 1717 | ||
| 1720 | /// Background colors for the generated default avatar, picked by the user id hash. Muted sage, | 1718 | /// Background colors for the generated default avatar, picked by the user id hash. Muted sage, |
crates/forge-web-base/src/accent.rsmodified+2 -65
| @@ -12,7 +12,7 @@ pub fn resolve(stored: &str) -> &'static Palette { | |||
| 12 | PALETTES | 12 | PALETTES |
| 13 | .iter() | 13 | .iter() |
| 14 | .find(|p| p.id == stored) | 14 | .find(|p| p.id == stored) |
| 15 | - .unwrap_or_else(default_palette) | 15 | + .unwrap_or(&PALETTES[0]) |
| 16 | } | 16 | } |
| 17 | 17 | ||
| 18 | /// The accent id a page shows for a stored one: the id itself when forge offers it (a preset or a | 18 | /// The accent id a page shows for a stored one: the id itself when forge offers it (a preset or a |
| @@ -38,7 +38,7 @@ pub fn resolve_base(stored: &str) -> &'static Base { | |||
| 38 | BASES | 38 | BASES |
| 39 | .iter() | 39 | .iter() |
| 40 | .find(|b| b.id == stored) | 40 | .find(|b| b.id == stored) |
| 41 | - .unwrap_or_else(default_base) | 41 | + .unwrap_or(&BASES[0]) |
| 42 | } | 42 | } |
| 43 | 43 | ||
| 44 | /// The base id a page shows for a stored one: the id itself when forge offers it (a preset or a | 44 | /// The base id a page shows for a stored one: the id itself when forge offers it (a preset or a |
| @@ -115,37 +115,6 @@ pub fn preset_base_hue(id: &str) -> Option<u16> { | |||
| 115 | .map(|b| custom_colour::hex_hue(b.light.bg)) | 115 | .map(|b| custom_colour::hex_hue(b.light.bg)) |
| 116 | } | 116 | } |
| 117 | 117 | ||
| 118 | -/// The `#RRGGBB` the picker shows for an accent id in one theme: the accent itself. A `hue-N` id | ||
| 119 | -/// gets the accent built for its hue; an id forge does not offer gets the default's. | ||
| 120 | -#[allow(dead_code)] // The settings picker shows its chips with this. | ||
| 121 | -pub fn swatch(id: &str, dark: bool) -> String { | ||
| 122 | - match custom_of(id, 50) { | ||
| 123 | - Some((hue, vivid)) => custom_colour::accent_tokens(hue, vivid, dark).accent, | ||
| 124 | - None => { | ||
| 125 | - let palette = resolve(id); | ||
| 126 | - let tokens = if dark { &palette.dark } else { &palette.light }; | ||
| 127 | - tokens.accent.to_owned() | ||
| 128 | - } | ||
| 129 | - } | ||
| 130 | -} | ||
| 131 | - | ||
| 132 | -/// The background and text colours the picker shows for a base id in one theme. A `hue-N` id gets | ||
| 133 | -/// the base built for its hue; an id forge does not offer gets the default's. | ||
| 134 | -#[allow(dead_code)] // The settings picker shows its chips with this. | ||
| 135 | -pub fn base_swatch(id: &str, dark: bool) -> (String, String) { | ||
| 136 | - match custom_of(id, 30) { | ||
| 137 | - Some((hue, vivid)) => { | ||
| 138 | - let tokens = custom_colour::base_tokens(hue, vivid, dark); | ||
| 139 | - (tokens.bg, tokens.text) | ||
| 140 | - } | ||
| 141 | - None => { | ||
| 142 | - let base = resolve_base(id); | ||
| 143 | - let tokens = if dark { &base.dark } else { &base.light }; | ||
| 144 | - (tokens.bg.to_owned(), tokens.text.to_owned()) | ||
| 145 | - } | ||
| 146 | - } | ||
| 147 | -} | ||
| 148 | - | ||
| 149 | /// The link to the stylesheet that styles the custom ids of one page, or None when none of the four | 118 | /// The link to the stylesheet that styles the custom ids of one page, or None when none of the four |
| 150 | /// is a hue (the presets are styled by the main stylesheet). The ids go in as given, so pass the | 119 | /// is a hue (the presets are styled by the main stylesheet). The ids go in as given, so pass the |
| 151 | /// ids a page shows (see `accent_id` and `base_id`). | 120 | /// ids a page shows (see `accent_id` and `base_id`). |
| @@ -165,20 +134,6 @@ pub fn custom_css_href( | |||
| 165 | }) | 134 | }) |
| 166 | } | 135 | } |
| 167 | 136 | ||
| 168 | -fn default_palette() -> &'static Palette { | ||
| 169 | - PALETTES | ||
| 170 | - .iter() | ||
| 171 | - .find(|p| p.id == DEFAULT) | ||
| 172 | - .expect("the default accent is one of the palettes") | ||
| 173 | -} | ||
| 174 | - | ||
| 175 | -fn default_base() -> &'static Base { | ||
| 176 | - BASES | ||
| 177 | - .iter() | ||
| 178 | - .find(|b| b.id == BASE_DEFAULT) | ||
| 179 | - .expect("the default base is one of the bases") | ||
| 180 | -} | ||
| 181 | - | ||
| 182 | #[cfg(test)] | 137 | #[cfg(test)] |
| 183 | mod tests { | 138 | mod tests { |
| 184 | use std::collections::HashSet; | 139 | use std::collections::HashSet; |
| @@ -397,24 +352,6 @@ mod tests { | |||
| 397 | assert_eq!(preset_base_hue("sage"), None); | 352 | assert_eq!(preset_base_hue("sage"), None); |
| 398 | } | 353 | } |
| 399 | 354 | ||
| 400 | - #[test] | ||
| 401 | - fn swatches_show_the_accent_and_the_base_for_presets_and_hues() { | ||
| 402 | - assert_eq!(swatch("sage", false), "#5E7D63"); | ||
| 403 | - assert_eq!(swatch("sage", true), "#93A663"); | ||
| 404 | - assert_eq!( | ||
| 405 | - swatch("hue-215", false), | ||
| 406 | - accent_tokens(215, 50, false).accent | ||
| 407 | - ); | ||
| 408 | - assert_eq!(swatch("hue-215", true), accent_tokens(215, 50, true).accent); | ||
| 409 | - // A removed id falls back to the default. | ||
| 410 | - assert_eq!(swatch("terracotta", false), swatch(DEFAULT, false)); | ||
| 411 | - let (bg, text) = base_swatch("blush", false); | ||
| 412 | - assert_eq!((bg.as_str(), text.as_str()), ("#F5EBEC", "#2B191C")); | ||
| 413 | - let (bg, text) = base_swatch("hue-215", true); | ||
| 414 | - assert_eq!(bg, base_tokens(215, 30, true).bg); | ||
| 415 | - assert_eq!(text, base_tokens(215, 30, true).text); | ||
| 416 | - } | ||
| 417 | - | ||
| 418 | #[test] | 355 | #[test] |
| 419 | fn the_custom_stylesheet_is_linked_only_when_a_hue_is_chosen() { | 356 | fn the_custom_stylesheet_is_linked_only_when_a_hue_is_chosen() { |
| 420 | assert_eq!(custom_css_href("sage", "plum", "blush", "ink"), None); | 357 | assert_eq!(custom_css_href("sage", "plum", "blush", "ink"), None); |
crates/forge-web-base/src/blobs.rsmodified+34 -38
| @@ -297,61 +297,57 @@ mod tests { | |||
| 297 | } | 297 | } |
| 298 | 298 | ||
| 299 | #[test] | 299 | #[test] |
| 300 | - fn fs_config_uses_blobs_under_data_dir() { | 300 | + fn remote_config_reads_the_secret_file() { |
| 301 | - let dir = tempfile::tempdir().unwrap(); | ||
| 302 | - let cfg = StorageConfig::default(); | ||
| 303 | - BlobStore::from_config(&cfg, dir.path()).unwrap(); | ||
| 304 | - assert!(dir.path().join("blobs").is_dir()); | ||
| 305 | - } | ||
| 306 | - | ||
| 307 | - #[test] | ||
| 308 | - fn s3_config_reads_the_secret_file() { | ||
| 309 | let dir = tempfile::tempdir().unwrap(); | 301 | let dir = tempfile::tempdir().unwrap(); |
| 310 | let secret = dir.path().join("secret"); | 302 | let secret = dir.path().join("secret"); |
| 311 | std::fs::write(&secret, "s3cret\n").unwrap(); | 303 | std::fs::write(&secret, "s3cret\n").unwrap(); |
| 312 | - let cfg = S3Config { | 304 | + let s3 = S3Config { |
| 313 | bucket: "forge".into(), | 305 | bucket: "forge".into(), |
| 314 | region: "us-east-1".into(), | 306 | region: "us-east-1".into(), |
| 315 | endpoint: "http://127.0.0.1:9000".into(), | 307 | endpoint: "http://127.0.0.1:9000".into(), |
| 316 | prefix: "/forge/".into(), | 308 | prefix: "/forge/".into(), |
| 317 | access_key_id: "AKIA".into(), | 309 | access_key_id: "AKIA".into(), |
| 318 | - secret_access_key_file: secret, | 310 | + secret_access_key_file: secret.clone(), |
| 319 | allow_http: true, | 311 | allow_http: true, |
| 320 | virtual_hosted_style: false, | 312 | virtual_hosted_style: false, |
| 321 | }; | 313 | }; |
| 322 | - assert!(BlobStore::s3(&cfg).is_ok()); | 314 | + let r2 = R2Config { |
| 323 | - let missing = S3Config { | 315 | + account_id: "0123abcd".into(), |
| 324 | - secret_access_key_file: dir.path().join("absent"), | 316 | + bucket: "forge".into(), |
| 325 | - ..cfg | 317 | + jurisdiction: "eu".into(), |
| 318 | + prefix: "/forge/".into(), | ||
| 319 | + access_key_id: "AKIA".into(), | ||
| 320 | + secret_access_key_file: secret, | ||
| 326 | }; | 321 | }; |
| 327 | - assert!(BlobStore::s3(&missing).is_err()); | 322 | + let s3_cfg = StorageConfig { |
| 328 | - } | 323 | + backend: StorageBackend::S3, |
| 329 | - | 324 | + s3: s3.clone(), |
| 330 | - #[test] | 325 | + ..StorageConfig::default() |
| 331 | - fn r2_config_builds_a_store_from_the_secret_file() { | 326 | + }; |
| 332 | - let dir = tempfile::tempdir().unwrap(); | 327 | + let r2_cfg = StorageConfig { |
| 333 | - let secret = dir.path().join("secret"); | ||
| 334 | - std::fs::write(&secret, "r2s3cret\n").unwrap(); | ||
| 335 | - let cfg = StorageConfig { | ||
| 336 | backend: StorageBackend::R2, | 328 | backend: StorageBackend::R2, |
| 337 | - r2: R2Config { | 329 | + r2: r2.clone(), |
| 338 | - account_id: "0123abcd".into(), | ||
| 339 | - bucket: "forge".into(), | ||
| 340 | - jurisdiction: "eu".into(), | ||
| 341 | - prefix: "/forge/".into(), | ||
| 342 | - access_key_id: "AKIA".into(), | ||
| 343 | - secret_access_key_file: secret, | ||
| 344 | - }, | ||
| 345 | ..StorageConfig::default() | 330 | ..StorageConfig::default() |
| 346 | }; | 331 | }; |
| 347 | - BlobStore::from_config(&cfg, dir.path()).unwrap(); | 332 | + assert!(BlobStore::from_config(&s3_cfg, dir.path()).is_ok()); |
| 348 | - let missing = StorageConfig { | 333 | + assert!(BlobStore::from_config(&r2_cfg, dir.path()).is_ok()); |
| 334 | + | ||
| 335 | + let absent = dir.path().join("absent"); | ||
| 336 | + let missing_s3 = StorageConfig { | ||
| 337 | + s3: S3Config { | ||
| 338 | + secret_access_key_file: absent.clone(), | ||
| 339 | + ..s3 | ||
| 340 | + }, | ||
| 341 | + ..s3_cfg | ||
| 342 | + }; | ||
| 343 | + let missing_r2 = StorageConfig { | ||
| 349 | r2: R2Config { | 344 | r2: R2Config { |
| 350 | - secret_access_key_file: dir.path().join("absent"), | 345 | + secret_access_key_file: absent, |
| 351 | - ..cfg.r2.clone() | 346 | + ..r2 |
| 352 | }, | 347 | }, |
| 353 | - ..cfg | 348 | + ..r2_cfg |
| 354 | }; | 349 | }; |
| 355 | - assert!(BlobStore::from_config(&missing, dir.path()).is_err()); | 350 | + assert!(BlobStore::from_config(&missing_s3, dir.path()).is_err()); |
| 351 | + assert!(BlobStore::from_config(&missing_r2, dir.path()).is_err()); | ||
| 356 | } | 352 | } |
| 357 | } | 353 | } |
crates/forge-web-base/src/custom_colour.rsmodified+3 -26
| @@ -1,11 +1,3 @@ | |||
| 1 | -//! Colours for any hue. A stored `hue-N` id (see `accent::hue_of`) is not a row of | ||
| 2 | -//! `accent_palette.rs`: its colours are built here from the OKLCH hue N, in the same roles a preset | ||
| 3 | -//! has. The accent sits at one lightness and chroma, with black or white text by contrast. The | ||
| 4 | -//! background is a neutral with a little chroma toward the hue. `stylesheet` writes the rules that | ||
| 5 | -//! apply them, in the shape `build.rs` writes for the presets. | ||
| 6 | - | ||
| 7 | -/// The colours of one accent in one theme: the fields of `accent_palette::Tokens`, owned, because a | ||
| 8 | -/// hue is built at run time. | ||
| 9 | #[derive(Debug, Clone)] | 1 | #[derive(Debug, Clone)] |
| 10 | pub struct OwnedTokens { | 2 | pub struct OwnedTokens { |
| 11 | pub accent: String, | 3 | pub accent: String, |
| @@ -38,7 +30,6 @@ impl OwnedTokens { | |||
| 38 | } | 30 | } |
| 39 | } | 31 | } |
| 40 | 32 | ||
| 41 | -/// The neutral colours of one base in one theme: the fields of `accent_palette::BaseTokens`, owned. | ||
| 42 | #[derive(Debug, Clone)] | 33 | #[derive(Debug, Clone)] |
| 43 | pub struct OwnedBaseTokens { | 34 | pub struct OwnedBaseTokens { |
| 44 | pub bg: String, | 35 | pub bg: String, |
| @@ -75,14 +66,11 @@ impl OwnedBaseTokens { | |||
| 75 | } | 66 | } |
| 76 | } | 67 | } |
| 77 | 68 | ||
| 78 | -/// Chroma of the neutrals: small, like the bases on offer. | ||
| 79 | const NEUTRAL_CHROMA: f64 = 0.012; | 69 | const NEUTRAL_CHROMA: f64 = 0.012; |
| 80 | 70 | ||
| 81 | -/// Slack for float error when testing whether a colour is inside sRGB. | ||
| 82 | const GAMUT_EPS: f64 = 1e-6; | 71 | const GAMUT_EPS: f64 = 1e-6; |
| 83 | 72 | ||
| 84 | -/// The chroma factor of an accent at vividness `vivid` (0..=100). The default, 50, gives exactly 1.0 | 73 | +/// The default, 50, gives exactly 1.0 so the legacy `hue-N` colours stay byte-identical. |
| 85 | -/// so the legacy `hue-N` colours stay byte-identical. | ||
| 86 | fn accent_factor(vivid: u8) -> f64 { | 74 | fn accent_factor(vivid: u8) -> f64 { |
| 87 | if vivid == 50 { | 75 | if vivid == 50 { |
| 88 | return 1.0; | 76 | return 1.0; |
| @@ -139,7 +127,6 @@ pub fn base_tokens(hue: u16, vivid: u8, dark: bool) -> OwnedBaseTokens { | |||
| 139 | tokens | 127 | tokens |
| 140 | } | 128 | } |
| 141 | 129 | ||
| 142 | -/// True when the text, the surface and the muted colour all read at 4.5:1 or more on the background. | ||
| 143 | fn base_is_readable(tokens: &OwnedBaseTokens) -> bool { | 130 | fn base_is_readable(tokens: &OwnedBaseTokens) -> bool { |
| 144 | const MIN: f64 = 4.5; | 131 | const MIN: f64 = 4.5; |
| 145 | contrast_ratio(&tokens.text, &tokens.bg) >= MIN | 132 | contrast_ratio(&tokens.text, &tokens.bg) >= MIN |
| @@ -147,7 +134,6 @@ fn base_is_readable(tokens: &OwnedBaseTokens) -> bool { | |||
| 147 | && contrast_ratio(&tokens.muted, &tokens.bg) >= MIN | 134 | && contrast_ratio(&tokens.muted, &tokens.bg) >= MIN |
| 148 | } | 135 | } |
| 149 | 136 | ||
| 150 | -/// The neutral colours of a base at one chroma factor (1.0 is the default vividness). | ||
| 151 | fn base_tokens_at(hue: u16, factor: f64, dark: bool) -> OwnedBaseTokens { | 137 | fn base_tokens_at(hue: u16, factor: f64, dark: bool) -> OwnedBaseTokens { |
| 152 | let h = f64::from(hue); | 138 | let h = f64::from(hue); |
| 153 | let n = |l: f64| colour(l, NEUTRAL_CHROMA * factor, h); | 139 | let n = |l: f64| colour(l, NEUTRAL_CHROMA * factor, h); |
| @@ -197,14 +183,12 @@ pub fn colour(lightness: f64, chroma: f64, hue: f64) -> String { | |||
| 197 | format!("#{r:02X}{g:02X}{b:02X}") | 183 | format!("#{r:02X}{g:02X}{b:02X}") |
| 198 | } | 184 | } |
| 199 | 185 | ||
| 200 | -/// The OKLCH hue of a `#RRGGBB` colour, rounded to a whole degree in `0..360`. | 186 | +#[allow(dead_code)] |
| 201 | -#[allow(dead_code)] // Used by the preset hues, which the settings picker reads. | ||
| 202 | pub fn hex_hue(hex: &str) -> u16 { | 187 | pub fn hex_hue(hex: &str) -> u16 { |
| 203 | let (_, _, hue) = linear_to_oklch(hex_linear(hex)); | 188 | let (_, _, hue) = linear_to_oklch(hex_linear(hex)); |
| 204 | (hue.round() as u16) % 360 | 189 | (hue.round() as u16) % 360 |
| 205 | } | 190 | } |
| 206 | 191 | ||
| 207 | -/// The WCAG contrast ratio between two `#RRGGBB` colours. | ||
| 208 | pub fn contrast_ratio(a: &str, b: &str) -> f64 { | 192 | pub fn contrast_ratio(a: &str, b: &str) -> f64 { |
| 209 | let (x, y) = (relative_luminance(a), relative_luminance(b)); | 193 | let (x, y) = (relative_luminance(a), relative_luminance(b)); |
| 210 | (x.max(y) + 0.05) / (x.min(y) + 0.05) | 194 | (x.max(y) + 0.05) / (x.min(y) + 0.05) |
| @@ -257,7 +241,6 @@ pub fn stylesheet( | |||
| 257 | css | 241 | css |
| 258 | } | 242 | } |
| 259 | 243 | ||
| 260 | -/// Appends `selector { … }` with one `--token: value;` line per declaration. `indent` is 0 or 2. | ||
| 261 | fn rule(css: &mut String, indent: &str, selector: &str, decls: &[(&str, &str)]) { | 244 | fn rule(css: &mut String, indent: &str, selector: &str, decls: &[(&str, &str)]) { |
| 262 | css.push_str(&format!("{indent}{selector} {{\n")); | 245 | css.push_str(&format!("{indent}{selector} {{\n")); |
| 263 | for (name, value) in decls { | 246 | for (name, value) in decls { |
| @@ -280,7 +263,6 @@ fn dark_rules(css: &mut String, selector: &str, decls: &[(&str, &str)]) { | |||
| 280 | rule(css, "", &format!("{selector}[data-theme=\"dark\"]"), decls); | 263 | rule(css, "", &format!("{selector}[data-theme=\"dark\"]"), decls); |
| 281 | } | 264 | } |
| 282 | 265 | ||
| 283 | -/// The text colour on a fill: white or near-black, whichever reads better. | ||
| 284 | fn text_on(fill: &str) -> String { | 266 | fn text_on(fill: &str) -> String { |
| 285 | const WHITE: &str = "#FFFFFF"; | 267 | const WHITE: &str = "#FFFFFF"; |
| 286 | const INK: &str = "#111111"; | 268 | const INK: &str = "#111111"; |
| @@ -291,7 +273,6 @@ fn text_on(fill: &str) -> String { | |||
| 291 | } | 273 | } |
| 292 | } | 274 | } |
| 293 | 275 | ||
| 294 | -/// The largest chroma up to `chroma` that fits sRGB at this lightness and hue. | ||
| 295 | fn fit_chroma(lightness: f64, chroma: f64, hue: f64) -> f64 { | 276 | fn fit_chroma(lightness: f64, chroma: f64, hue: f64) -> f64 { |
| 296 | if in_gamut(lightness, chroma, hue) { | 277 | if in_gamut(lightness, chroma, hue) { |
| 297 | return chroma; | 278 | return chroma; |
| @@ -330,8 +311,7 @@ fn oklch_to_linear(lightness: f64, chroma: f64, hue: f64) -> [f64; 3] { | |||
| 330 | ] | 311 | ] |
| 331 | } | 312 | } |
| 332 | 313 | ||
| 333 | -/// Linear sRGB to OKLCH: lightness, chroma and hue in degrees. | 314 | +#[allow(dead_code)] |
| 334 | -#[allow(dead_code)] // Used by `hex_hue`, which the settings picker reads through the preset hues. | ||
| 335 | fn linear_to_oklch([r, g, b]: [f64; 3]) -> (f64, f64, f64) { | 315 | fn linear_to_oklch([r, g, b]: [f64; 3]) -> (f64, f64, f64) { |
| 336 | let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt(); | 316 | let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt(); |
| 337 | let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt(); | 317 | let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt(); |
| @@ -360,7 +340,6 @@ fn hex_linear(hex: &str) -> [f64; 3] { | |||
| 360 | [channel(1), channel(3), channel(5)] | 340 | [channel(1), channel(3), channel(5)] |
| 361 | } | 341 | } |
| 362 | 342 | ||
| 363 | -/// sRGB transfer function, encoded value to linear light. | ||
| 364 | fn decode(v: f64) -> f64 { | 343 | fn decode(v: f64) -> f64 { |
| 365 | if v <= 0.040_45 { | 344 | if v <= 0.040_45 { |
| 366 | v / 12.92 | 345 | v / 12.92 |
| @@ -369,7 +348,6 @@ fn decode(v: f64) -> f64 { | |||
| 369 | } | 348 | } |
| 370 | } | 349 | } |
| 371 | 350 | ||
| 372 | -/// Linear light to the sRGB encoded value. | ||
| 373 | fn encode(v: f64) -> f64 { | 351 | fn encode(v: f64) -> f64 { |
| 374 | if v <= 0.003_130_8 { | 352 | if v <= 0.003_130_8 { |
| 375 | 12.92 * v | 353 | 12.92 * v |
| @@ -393,7 +371,6 @@ mod tests { | |||
| 393 | fn the_extremes_are_exact_and_a_preset_hue_reads_back() { | 371 | fn the_extremes_are_exact_and_a_preset_hue_reads_back() { |
| 394 | assert_eq!(colour(1.0, 0.0, 0.0), "#FFFFFF"); | 372 | assert_eq!(colour(1.0, 0.0, 0.0), "#FFFFFF"); |
| 395 | assert_eq!(colour(0.0, 0.0, 0.0), "#000000"); | 373 | assert_eq!(colour(0.0, 0.0, 0.0), "#000000"); |
| 396 | - // Sage is about 149 degrees; Ocean about 240. | ||
| 397 | assert_eq!(hex_hue("#5E7D63"), 149); | 374 | assert_eq!(hex_hue("#5E7D63"), 149); |
| 398 | assert_eq!(hex_hue("#467799"), 240); | 375 | assert_eq!(hex_hue("#467799"), 240); |
| 399 | } | 376 | } |
crates/forge-web-base/src/i18n/accounts.rsmodified+0 -6
| @@ -20,8 +20,6 @@ pub enum A { | |||
| 20 | AdminHelp, | 20 | AdminHelp, |
| 21 | GenerateLink, | 21 | GenerateLink, |
| 22 | ResetLinkReady, | 22 | ResetLinkReady, |
| 23 | - Disable2fa, | ||
| 24 | - Actions, | ||
| 25 | OkSuspended, | 23 | OkSuspended, |
| 26 | OkUnsuspended, | 24 | OkUnsuspended, |
| 27 | OkAdminOn, | 25 | OkAdminOn, |
| @@ -92,10 +90,6 @@ pub fn t(lang: Lang, key: A) -> &'static str { | |||
| 92 | (GenerateLink, Tr) => "Sıfırlama bağlantısı üret", | 90 | (GenerateLink, Tr) => "Sıfırlama bağlantısı üret", |
| 93 | (ResetLinkReady, En) => "One-time reset link. It is shown only now:", | 91 | (ResetLinkReady, En) => "One-time reset link. It is shown only now:", |
| 94 | (ResetLinkReady, Tr) => "Tek kullanımlık sıfırlama bağlantısı. Yalnızca şimdi gösterilir:", | 92 | (ResetLinkReady, Tr) => "Tek kullanımlık sıfırlama bağlantısı. Yalnızca şimdi gösterilir:", |
| 95 | - (Disable2fa, En) => "Disable two-factor", | ||
| 96 | - (Disable2fa, Tr) => "İki adımlı doğrulamayı kapat", | ||
| 97 | - (Actions, En) => "Actions", | ||
| 98 | - (Actions, Tr) => "İşlemler", | ||
| 99 | (OkSuspended, En) => "Account suspended.", | 93 | (OkSuspended, En) => "Account suspended.", |
| 100 | (OkSuspended, Tr) => "Hesap askıya alındı.", | 94 | (OkSuspended, Tr) => "Hesap askıya alındı.", |
| 101 | (OkUnsuspended, En) => "Suspension lifted.", | 95 | (OkUnsuspended, En) => "Suspension lifted.", |
crates/forge-web-base/src/i18n/alerts.rsmodified+2 -11
| @@ -76,12 +76,6 @@ pub fn body(lang: Lang, topic: &str, subject: &str, detail: &str, resolved: bool | |||
| 76 | (Lang::En, "runner_offline", true) => format!("Runner {subject} checked in again."), | 76 | (Lang::En, "runner_offline", true) => format!("Runner {subject} checked in again."), |
| 77 | (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden bağlandı."), | 77 | (Lang::Tr, "runner_offline", true) => format!("{subject} runner'ı yeniden bağlandı."), |
| 78 | 78 | ||
| 79 | - (Lang::En, "backup_failed" | "backup_verify_failed" | "fsck_failed", false) => { | ||
| 80 | - detail.to_owned() | ||
| 81 | - } | ||
| 82 | - (Lang::Tr, "backup_failed" | "backup_verify_failed" | "fsck_failed", false) => { | ||
| 83 | - detail.to_owned() | ||
| 84 | - } | ||
| 85 | (Lang::En, "backup_failed", true) => "The latest backup succeeded.".to_owned(), | 79 | (Lang::En, "backup_failed", true) => "The latest backup succeeded.".to_owned(), |
| 86 | (Lang::Tr, "backup_failed", true) => "Son yedekleme başarılı oldu.".to_owned(), | 80 | (Lang::Tr, "backup_failed", true) => "Son yedekleme başarılı oldu.".to_owned(), |
| 87 | (Lang::En, "backup_verify_failed", true) => { | 81 | (Lang::En, "backup_verify_failed", true) => { |
| @@ -168,11 +162,8 @@ pub fn settings_link(lang: Lang) -> &'static str { | |||
| 168 | } | 162 | } |
| 169 | 163 | ||
| 170 | /// Email subject: the title, tagged with the instance. | 164 | /// Email subject: the title, tagged with the instance. |
| 171 | -pub fn mail_subject(lang: Lang, title: &str) -> String { | 165 | +pub fn mail_subject(title: &str) -> String { |
| 172 | - match lang { | 166 | + format!("[forge] {title}") |
| 173 | - Lang::En => format!("[forge] {title}"), | ||
| 174 | - Lang::Tr => format!("[forge] {title}"), | ||
| 175 | - } | ||
| 176 | } | 167 | } |
| 177 | 168 | ||
| 178 | /// Email body: the explanation, then where to look. | 169 | /// Email body: the explanation, then where to look. |
crates/forge-web-base/src/i18n/authoring.rsmodified+0 -3
| @@ -14,7 +14,6 @@ pub enum K { | |||
| 14 | ReviewerNoAccess, | 14 | ReviewerNoAccess, |
| 15 | ReviewerIsAuthor, | 15 | ReviewerIsAuthor, |
| 16 | ReviewerAlready, | 16 | ReviewerAlready, |
| 17 | - ReviewRequestsTab, | ||
| 18 | } | 17 | } |
| 19 | 18 | ||
| 20 | pub fn t(lang: Lang, key: K) -> &'static str { | 19 | pub fn t(lang: Lang, key: K) -> &'static str { |
| @@ -41,8 +40,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 41 | (ReviewerIsAuthor, Tr) => "Yazar kendi değişiklik isteğini inceleyemez.", | 40 | (ReviewerIsAuthor, Tr) => "Yazar kendi değişiklik isteğini inceleyemez.", |
| 42 | (ReviewerAlready, En) => "A review is already requested from that user.", | 41 | (ReviewerAlready, En) => "A review is already requested from that user.", |
| 43 | (ReviewerAlready, Tr) => "Bu kullanıcıdan zaten inceleme istendi.", | 42 | (ReviewerAlready, Tr) => "Bu kullanıcıdan zaten inceleme istendi.", |
| 44 | - (ReviewRequestsTab, En) => "Review requests", | ||
| 45 | - (ReviewRequestsTab, Tr) => "İnceleme istekleri", | ||
| 46 | } | 43 | } |
| 47 | } | 44 | } |
| 48 | 45 | ||
crates/forge-web-base/src/i18n/browse.rsmodified+0 -10
| @@ -43,7 +43,6 @@ strings! { | |||
| 43 | PermalinkCopied => "Permalink copied", "Kalıcı bağlantı kopyalandı"; | 43 | PermalinkCopied => "Permalink copied", "Kalıcı bağlantı kopyalandı"; |
| 44 | 44 | ||
| 45 | GoToFile => "Go to file", "Dosyaya git"; | 45 | GoToFile => "Go to file", "Dosyaya git"; |
| 46 | - FinderTitle => "Go to file", "Dosyaya git"; | ||
| 47 | FinderPlaceholder => "Type to find a file", "Dosya bulmak için yazın"; | 46 | FinderPlaceholder => "Type to find a file", "Dosya bulmak için yazın"; |
| 48 | FinderHint => "Up and down to move, Enter to open, Esc to close", "Gezinmek için yukarı ve aşağı, açmak için Enter, kapatmak için Esc"; | 47 | FinderHint => "Up and down to move, Enter to open, Esc to close", "Gezinmek için yukarı ve aşağı, açmak için Enter, kapatmak için Esc"; |
| 49 | FinderEmpty => "No matching files", "Eşleşen dosya yok"; | 48 | FinderEmpty => "No matching files", "Eşleşen dosya yok"; |
| @@ -93,14 +92,6 @@ pub fn ahead_behind(lang: Lang, ahead: u32, behind: u32) -> String { | |||
| 93 | } | 92 | } |
| 94 | } | 93 | } |
| 95 | 94 | ||
| 96 | -/// "Delete branch `name`?" for the accessible name of the delete button. | ||
| 97 | -pub fn delete_aria(lang: Lang, name: &str) -> String { | ||
| 98 | - match lang { | ||
| 99 | - Lang::En => format!("Delete branch {name}"), | ||
| 100 | - Lang::Tr => format!("{name} dalını sil"), | ||
| 101 | - } | ||
| 102 | -} | ||
| 103 | - | ||
| 104 | /// Shown when blame has a file of `size` bytes over the limit. | 95 | /// Shown when blame has a file of `size` bytes over the limit. |
| 105 | pub fn blame_limit(lang: Lang, limit: &str) -> String { | 96 | pub fn blame_limit(lang: Lang, limit: &str) -> String { |
| 106 | match lang { | 97 | match lang { |
| @@ -136,7 +127,6 @@ mod tests { | |||
| 136 | #[test] | 127 | #[test] |
| 137 | fn helpers_carry_their_arguments() { | 128 | fn helpers_carry_their_arguments() { |
| 138 | assert_eq!(ahead_behind(Lang::En, 3, 1), "3 ahead, 1 behind"); | 129 | assert_eq!(ahead_behind(Lang::En, 3, 1), "3 ahead, 1 behind"); |
| 139 | - assert!(delete_aria(Lang::Tr, "x").contains('x')); | ||
| 140 | assert!(blame_limit(Lang::En, "1 MiB").contains("1 MiB")); | 130 | assert!(blame_limit(Lang::En, "1 MiB").contains("1 MiB")); |
| 141 | } | 131 | } |
| 142 | } | 132 | } |
crates/forge-web-base/src/i18n/code.rsmodified+3 -15
| @@ -31,7 +31,6 @@ pub enum K { | |||
| 31 | EmptyRepoPush, | 31 | EmptyRepoPush, |
| 32 | OverHttps, | 32 | OverHttps, |
| 33 | OverSsh, | 33 | OverSsh, |
| 34 | - DownloadNav, | ||
| 35 | DownloadZip, | 34 | DownloadZip, |
| 36 | DownloadTarGz, | 35 | DownloadTarGz, |
| 37 | RecentPushes, | 36 | RecentPushes, |
| @@ -175,8 +174,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 175 | (OverHttps, Tr) => "HTTPS üzerinden", | 174 | (OverHttps, Tr) => "HTTPS üzerinden", |
| 176 | (OverSsh, En) => "Over SSH", | 175 | (OverSsh, En) => "Over SSH", |
| 177 | (OverSsh, Tr) => "SSH üzerinden", | 176 | (OverSsh, Tr) => "SSH üzerinden", |
| 178 | - (DownloadNav, En) => "Download", | ||
| 179 | - (DownloadNav, Tr) => "İndir", | ||
| 180 | (DownloadZip, En) => "Download ZIP", | 177 | (DownloadZip, En) => "Download ZIP", |
| 181 | (DownloadZip, Tr) => "ZIP olarak indir", | 178 | (DownloadZip, Tr) => "ZIP olarak indir", |
| 182 | (DownloadTarGz, En) => "Download tar.gz", | 179 | (DownloadTarGz, En) => "Download tar.gz", |
| @@ -458,14 +455,6 @@ pub fn signed_by(lang: Lang, signer: &str, key: &str) -> String { | |||
| 458 | } | 455 | } |
| 459 | } | 456 | } |
| 460 | 457 | ||
| 461 | -/// `Page <n>` for the commit list pager. | ||
| 462 | -pub fn page_label(lang: Lang, page: u32) -> String { | ||
| 463 | - match lang { | ||
| 464 | - Lang::En => format!("Page {page}"), | ||
| 465 | - Lang::Tr => format!("Sayfa {page}"), | ||
| 466 | - } | ||
| 467 | -} | ||
| 468 | - | ||
| 469 | /// The star button label: `Unstar <n>` when starred, `★ Star <n>` otherwise. | 458 | /// The star button label: `Unstar <n>` when starred, `★ Star <n>` otherwise. |
| 470 | pub fn star_label(lang: Lang, starred: bool, stars: u64) -> String { | 459 | pub fn star_label(lang: Lang, starred: bool, stars: u64) -> String { |
| 471 | match (lang, starred) { | 460 | match (lang, starred) { |
| @@ -501,10 +490,10 @@ pub fn forks_count(lang: Lang, forks: u64) -> String { | |||
| 501 | } | 490 | } |
| 502 | 491 | ||
| 503 | /// The mirror status after a successful sync. | 492 | /// The mirror status after a successful sync. |
| 504 | -pub fn mirror_synced(lang: Lang) -> (&'static str, &'static str) { | 493 | +pub fn mirror_synced(lang: Lang) -> &'static str { |
| 505 | match lang { | 494 | match lang { |
| 506 | - Lang::En => ("last synced ", ""), | 495 | + Lang::En => "last synced ", |
| 507 | - Lang::Tr => ("son eşitleme: ", ""), | 496 | + Lang::Tr => "son eşitleme: ", |
| 508 | } | 497 | } |
| 509 | } | 498 | } |
| 510 | 499 | ||
| @@ -544,7 +533,6 @@ mod tests { | |||
| 544 | K::EmptyRepoPush, | 533 | K::EmptyRepoPush, |
| 545 | K::OverHttps, | 534 | K::OverHttps, |
| 546 | K::OverSsh, | 535 | K::OverSsh, |
| 547 | - K::DownloadNav, | ||
| 548 | K::DownloadZip, | 536 | K::DownloadZip, |
| 549 | K::DownloadTarGz, | 537 | K::DownloadTarGz, |
| 550 | K::RecentPushes, | 538 | K::RecentPushes, |
crates/forge-web-base/src/i18n/community.rsmodified+1 -38
| @@ -1,14 +1,9 @@ | |||
| 1 | -//! Strings for the community group: discussions, the wiki and snippets. See `super` for the | ||
| 2 | -//! pattern: one variant per UI phrase, an exhaustive `t` match, and small helpers for sentences | ||
| 3 | -//! that carry arguments. | ||
| 4 | - | ||
| 5 | use forge_core::discussions::DiscussionCategory; | 1 | use forge_core::discussions::DiscussionCategory; |
| 6 | 2 | ||
| 7 | use super::Lang; | 3 | use super::Lang; |
| 8 | 4 | ||
| 9 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 5 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 10 | pub enum K { | 6 | pub enum K { |
| 11 | - // Discussions: list, new, view and settings. | ||
| 12 | AllCategories, | 7 | AllCategories, |
| 13 | CategoriesNav, | 8 | CategoriesNav, |
| 14 | NewDiscussion, | 9 | NewDiscussion, |
| @@ -48,8 +43,6 @@ pub enum K { | |||
| 48 | CategoryIdeas, | 43 | CategoryIdeas, |
| 49 | CategoryQa, | 44 | CategoryQa, |
| 50 | CategoryAnnouncements, | 45 | CategoryAnnouncements, |
| 51 | - | ||
| 52 | - // Wiki. | ||
| 53 | Wiki, | 46 | Wiki, |
| 54 | Home, | 47 | Home, |
| 55 | AllPages, | 48 | AllPages, |
| @@ -69,8 +62,6 @@ pub enum K { | |||
| 69 | PageExists, | 62 | PageExists, |
| 70 | WikiConflict, | 63 | WikiConflict, |
| 71 | WikiPages, | 64 | WikiPages, |
| 72 | - | ||
| 73 | - // Snippets. | ||
| 74 | Snippets, | 65 | Snippets, |
| 75 | NewSnippet, | 66 | NewSnippet, |
| 76 | NoSnippets, | 67 | NoSnippets, |
| @@ -294,7 +285,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 294 | } | 285 | } |
| 295 | } | 286 | } |
| 296 | 287 | ||
| 297 | -/// The name of a discussion category, as the list, the form and the discussion show it. | ||
| 298 | pub fn category_label(lang: Lang, category: DiscussionCategory) -> &'static str { | 288 | pub fn category_label(lang: Lang, category: DiscussionCategory) -> &'static str { |
| 299 | match category { | 289 | match category { |
| 300 | DiscussionCategory::General => t(lang, K::CategoryGeneral), | 290 | DiscussionCategory::General => t(lang, K::CategoryGeneral), |
| @@ -304,9 +294,6 @@ pub fn category_label(lang: Lang, category: DiscussionCategory) -> &'static str | |||
| 304 | } | 294 | } |
| 305 | } | 295 | } |
| 306 | 296 | ||
| 307 | -/// The byline of a discussion row, split around the author and the time. English reads | ||
| 308 | -/// `by Ali 3 days ago`; Turkish reads `Ali tarafından 3 gün önce açıldı`. Returns the text | ||
| 309 | -/// before the author, between the author and the time, and after the time. | ||
| 310 | pub fn byline(lang: Lang) -> (&'static str, &'static str, &'static str) { | 297 | pub fn byline(lang: Lang) -> (&'static str, &'static str, &'static str) { |
| 311 | match lang { | 298 | match lang { |
| 312 | Lang::En => (" by ", " ", ""), | 299 | Lang::En => (" by ", " ", ""), |
| @@ -314,15 +301,6 @@ pub fn byline(lang: Lang) -> (&'static str, &'static str, &'static str) { | |||
| 314 | } | 301 | } |
| 315 | } | 302 | } |
| 316 | 303 | ||
| 317 | -/// `Page 3` / `Sayfa 3`. | ||
| 318 | -pub fn page_number(lang: Lang, page: u32) -> String { | ||
| 319 | - match lang { | ||
| 320 | - Lang::En => format!("Page {page}"), | ||
| 321 | - Lang::Tr => format!("Sayfa {page}"), | ||
| 322 | - } | ||
| 323 | -} | ||
| 324 | - | ||
| 325 | -/// `1 comment` / `3 comments` in a list row, and `3 yorum` in Turkish. | ||
| 326 | pub fn comments_count(lang: Lang, count: i64) -> String { | 304 | pub fn comments_count(lang: Lang, count: i64) -> String { |
| 327 | match lang { | 305 | match lang { |
| 328 | Lang::En => format!("{count} comment{}", if count == 1 { "" } else { "s" }), | 306 | Lang::En => format!("{count} comment{}", if count == 1 { "" } else { "s" }), |
| @@ -330,15 +308,6 @@ pub fn comments_count(lang: Lang, count: i64) -> String { | |||
| 330 | } | 308 | } |
| 331 | } | 309 | } |
| 332 | 310 | ||
| 333 | -/// `1 comment` / `3 comments` in a discussion header, and `3 yorum` in Turkish. | ||
| 334 | -pub fn comments_total(lang: Lang, count: i64) -> String { | ||
| 335 | - match lang { | ||
| 336 | - Lang::En => format!("{count} comment{}", if count == 1 { "" } else { "s" }), | ||
| 337 | - Lang::Tr => format!("{count} yorum"), | ||
| 338 | - } | ||
| 339 | -} | ||
| 340 | - | ||
| 341 | -/// The text before the "Log in" link of a sign-in prompt. English has none. | ||
| 342 | pub fn comment_login_lead(lang: Lang) -> &'static str { | 311 | pub fn comment_login_lead(lang: Lang) -> &'static str { |
| 343 | match lang { | 312 | match lang { |
| 344 | Lang::En => "", | 313 | Lang::En => "", |
| @@ -346,7 +315,6 @@ pub fn comment_login_lead(lang: Lang) -> &'static str { | |||
| 346 | } | 315 | } |
| 347 | } | 316 | } |
| 348 | 317 | ||
| 349 | -/// `The page is larger than 1048576 bytes.` / `Sayfa 1048576 bayttan büyük.` | ||
| 350 | pub fn page_too_large(lang: Lang, max: usize) -> String { | 318 | pub fn page_too_large(lang: Lang, max: usize) -> String { |
| 351 | match lang { | 319 | match lang { |
| 352 | Lang::En => format!("The page is larger than {max} bytes."), | 320 | Lang::En => format!("The page is larger than {max} bytes."), |
| @@ -354,7 +322,6 @@ pub fn page_too_large(lang: Lang, max: usize) -> String { | |||
| 354 | } | 322 | } |
| 355 | } | 323 | } |
| 356 | 324 | ||
| 357 | -/// Words before a relative update time: `updated ` in English. Turkish puts the time first. | ||
| 358 | pub fn updated_before(lang: Lang) -> &'static str { | 325 | pub fn updated_before(lang: Lang) -> &'static str { |
| 359 | match lang { | 326 | match lang { |
| 360 | Lang::En => "updated ", | 327 | Lang::En => "updated ", |
| @@ -362,7 +329,6 @@ pub fn updated_before(lang: Lang) -> &'static str { | |||
| 362 | } | 329 | } |
| 363 | } | 330 | } |
| 364 | 331 | ||
| 365 | -/// Words after a relative update time: ` güncellendi` in Turkish. English puts the time last. | ||
| 366 | pub fn updated_after(lang: Lang) -> &'static str { | 332 | pub fn updated_after(lang: Lang) -> &'static str { |
| 367 | match lang { | 333 | match lang { |
| 368 | Lang::En => "", | 334 | Lang::En => "", |
| @@ -370,7 +336,6 @@ pub fn updated_after(lang: Lang) -> &'static str { | |||
| 370 | } | 336 | } |
| 371 | } | 337 | } |
| 372 | 338 | ||
| 373 | -/// `2 files` / `1 file` / `2 dosya`. | ||
| 374 | pub fn files_count(lang: Lang, count: u64) -> String { | 339 | pub fn files_count(lang: Lang, count: u64) -> String { |
| 375 | match lang { | 340 | match lang { |
| 376 | Lang::En => format!("{count} {}", if count == 1 { "file" } else { "files" }), | 341 | Lang::En => format!("{count} {}", if count == 1 { "file" } else { "files" }), |
| @@ -378,7 +343,6 @@ pub fn files_count(lang: Lang, count: u64) -> String { | |||
| 378 | } | 343 | } |
| 379 | } | 344 | } |
| 380 | 345 | ||
| 381 | -/// `1 of 10 files · 1 MiB max` / `1 / 10 dosya · en fazla 1 MiB`. | ||
| 382 | pub fn files_limit(lang: Lang, count: usize, max_files: usize, max_mib: usize) -> String { | 346 | pub fn files_limit(lang: Lang, count: usize, max_files: usize, max_mib: usize) -> String { |
| 383 | match lang { | 347 | match lang { |
| 384 | Lang::En => format!("{count} of {max_files} files · {max_mib} MiB max"), | 348 | Lang::En => format!("{count} of {max_files} files · {max_mib} MiB max"), |
| @@ -386,7 +350,6 @@ pub fn files_limit(lang: Lang, count: usize, max_files: usize, max_mib: usize) - | |||
| 386 | } | 350 | } |
| 387 | } | 351 | } |
| 388 | 352 | ||
| 389 | -/// `Revisions of Home` / `Home revizyonları`. | ||
| 390 | pub fn revisions_of(lang: Lang, title: &str) -> String { | 353 | pub fn revisions_of(lang: Lang, title: &str) -> String { |
| 391 | match lang { | 354 | match lang { |
| 392 | Lang::En => format!("Revisions of {title}"), | 355 | Lang::En => format!("Revisions of {title}"), |
| @@ -511,7 +474,7 @@ mod tests { | |||
| 511 | assert_eq!(comments_count(Lang::En, 1), "1 comment"); | 474 | assert_eq!(comments_count(Lang::En, 1), "1 comment"); |
| 512 | assert_eq!(comments_count(Lang::En, 3), "3 comments"); | 475 | assert_eq!(comments_count(Lang::En, 3), "3 comments"); |
| 513 | assert_eq!(comments_count(Lang::Tr, 3), "3 yorum"); | 476 | assert_eq!(comments_count(Lang::Tr, 3), "3 yorum"); |
| 514 | - assert_eq!(page_number(Lang::Tr, 2), "Sayfa 2"); | 477 | + assert_eq!(crate::i18n::page_label(Lang::Tr, 2), "Sayfa 2"); |
| 515 | assert_eq!(files_count(Lang::En, 2), "2 files"); | 478 | assert_eq!(files_count(Lang::En, 2), "2 files"); |
| 516 | assert_eq!(files_count(Lang::En, 1), "1 file"); | 479 | assert_eq!(files_count(Lang::En, 1), "1 file"); |
| 517 | } | 480 | } |
crates/forge-web-base/src/i18n/integrations.rsmodified+0 -24
| @@ -51,7 +51,6 @@ pub enum K { | |||
| 51 | NoWebhooks, | 51 | NoWebhooks, |
| 52 | NoneYet, | 52 | NoneYet, |
| 53 | NoResponse, | 53 | NoResponse, |
| 54 | - NoticeConfirm, | ||
| 55 | NoticeCreated, | 54 | NoticeCreated, |
| 56 | NoticeDeleted, | 55 | NoticeDeleted, |
| 57 | NoticePullCreated, | 56 | NoticePullCreated, |
| @@ -79,7 +78,6 @@ pub enum K { | |||
| 79 | SendTestPing, | 78 | SendTestPing, |
| 80 | StateFailed, | 79 | StateFailed, |
| 81 | StateGaveUp, | 80 | StateGaveUp, |
| 82 | - StateOk, | ||
| 83 | StatePending, | 81 | StatePending, |
| 84 | Status, | 82 | Status, |
| 85 | StatusFailed, | 83 | StatusFailed, |
| @@ -142,7 +140,6 @@ pub const ALL: &[K] = &[ | |||
| 142 | K::NoWebhooks, | 140 | K::NoWebhooks, |
| 143 | K::NoneYet, | 141 | K::NoneYet, |
| 144 | K::NoResponse, | 142 | K::NoResponse, |
| 145 | - K::NoticeConfirm, | ||
| 146 | K::NoticeCreated, | 143 | K::NoticeCreated, |
| 147 | K::NoticeDeleted, | 144 | K::NoticeDeleted, |
| 148 | K::NoticePullCreated, | 145 | K::NoticePullCreated, |
| @@ -170,7 +167,6 @@ pub const ALL: &[K] = &[ | |||
| 170 | K::SendTestPing, | 167 | K::SendTestPing, |
| 171 | K::StateFailed, | 168 | K::StateFailed, |
| 172 | K::StateGaveUp, | 169 | K::StateGaveUp, |
| 173 | - K::StateOk, | ||
| 174 | K::StatePending, | 170 | K::StatePending, |
| 175 | K::Status, | 171 | K::Status, |
| 176 | K::StatusFailed, | 172 | K::StatusFailed, |
| @@ -297,8 +293,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 297 | (NoneYet, Tr) => "henüz yok", | 293 | (NoneYet, Tr) => "henüz yok", |
| 298 | (NoResponse, En) => "no response", | 294 | (NoResponse, En) => "no response", |
| 299 | (NoResponse, Tr) => "yanıt yok", | 295 | (NoResponse, Tr) => "yanıt yok", |
| 300 | - (NoticeConfirm, En) => "The delete was not confirmed. Nothing was deleted.", | ||
| 301 | - (NoticeConfirm, Tr) => "Silme onaylanmadı. Hiçbir şey silinmedi.", | ||
| 302 | (NoticeCreated, En) => { | 296 | (NoticeCreated, En) => { |
| 303 | "Push mirror created. It will be pushed after the next push or on its interval." | 297 | "Push mirror created. It will be pushed after the next push or on its interval." |
| 304 | } | 298 | } |
| @@ -365,8 +359,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 365 | (StateFailed, Tr) => "başarısız, yeniden denenecek", | 359 | (StateFailed, Tr) => "başarısız, yeniden denenecek", |
| 366 | (StateGaveUp, En) => "gave up", | 360 | (StateGaveUp, En) => "gave up", |
| 367 | (StateGaveUp, Tr) => "vazgeçildi", | 361 | (StateGaveUp, Tr) => "vazgeçildi", |
| 368 | - (StateOk, En) => "ok", | ||
| 369 | - (StateOk, Tr) => "tamam", | ||
| 370 | (StatePending, En) => "pending", | 362 | (StatePending, En) => "pending", |
| 371 | (StatePending, Tr) => "beklemede", | 363 | (StatePending, Tr) => "beklemede", |
| 372 | (Status, En) => "Status", | 364 | (Status, En) => "Status", |
| @@ -448,18 +440,6 @@ pub fn every_minutes(lang: Lang, minutes: u32) -> String { | |||
| 448 | } | 440 | } |
| 449 | } | 441 | } |
| 450 | 442 | ||
| 451 | -/// "The last 50 deliveries. Open one to see what was sent and what came back." | ||
| 452 | -pub fn recent_deliveries(lang: Lang, shown: u32) -> String { | ||
| 453 | - match lang { | ||
| 454 | - Lang::En => format!( | ||
| 455 | - "The last {shown} deliveries. Open one to see what was sent and what came back." | ||
| 456 | - ), | ||
| 457 | - Lang::Tr => { | ||
| 458 | - format!("Son {shown} teslimat. Birini açıp gönderileni ve alınan yanıtı görün.") | ||
| 459 | - } | ||
| 460 | - } | ||
| 461 | -} | ||
| 462 | - | ||
| 463 | #[cfg(test)] | 443 | #[cfg(test)] |
| 464 | mod tests { | 444 | mod tests { |
| 465 | use super::*; | 445 | use super::*; |
| @@ -485,9 +465,5 @@ mod tests { | |||
| 485 | fn helpers_keep_english_wording() { | 465 | fn helpers_keep_english_wording() { |
| 486 | assert_eq!(every_hours(Lang::En, 8), "every 8 h"); | 466 | assert_eq!(every_hours(Lang::En, 8), "every 8 h"); |
| 487 | assert_eq!(every_minutes(Lang::En, 90), "every 90 min"); | 467 | assert_eq!(every_minutes(Lang::En, 90), "every 90 min"); |
| 488 | - assert_eq!( | ||
| 489 | - recent_deliveries(Lang::En, 50), | ||
| 490 | - "The last 50 deliveries. Open one to see what was sent and what came back." | ||
| 491 | - ); | ||
| 492 | } | 468 | } |
| 493 | } | 469 | } |
crates/forge-web-base/src/i18n/issues.rsmodified+2 -59
| @@ -3,7 +3,6 @@ | |||
| 3 | 3 | ||
| 4 | use super::Lang; | 4 | use super::Lang; |
| 5 | 5 | ||
| 6 | -#[allow(dead_code)] | ||
| 7 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 6 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 8 | pub enum K { | 7 | pub enum K { |
| 9 | // Shared labels and buttons. | 8 | // Shared labels and buttons. |
| @@ -22,7 +21,6 @@ pub enum K { | |||
| 22 | Name, | 21 | Name, |
| 23 | Color, | 22 | Color, |
| 24 | Reason, | 23 | Reason, |
| 25 | - None, | ||
| 26 | Open, | 24 | Open, |
| 27 | Closed, | 25 | Closed, |
| 28 | Search, | 26 | Search, |
| @@ -150,8 +148,6 @@ pub enum K { | |||
| 150 | SearchTitles, | 148 | SearchTitles, |
| 151 | FiltersApplied, | 149 | FiltersApplied, |
| 152 | ClearFilters, | 150 | ClearFilters, |
| 153 | - Opened, | ||
| 154 | - By, | ||
| 155 | ChooseTemplate, | 151 | ChooseTemplate, |
| 156 | BlankIssue, | 152 | BlankIssue, |
| 157 | SubmitNewIssue, | 153 | SubmitNewIssue, |
| @@ -206,8 +202,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 206 | (K::Color, Lang::Tr) => "Renk", | 202 | (K::Color, Lang::Tr) => "Renk", |
| 207 | (K::Reason, Lang::En) => "Reason", | 203 | (K::Reason, Lang::En) => "Reason", |
| 208 | (K::Reason, Lang::Tr) => "Neden", | 204 | (K::Reason, Lang::Tr) => "Neden", |
| 209 | - (K::None, Lang::En) => "None", | ||
| 210 | - (K::None, Lang::Tr) => "Yok", | ||
| 211 | (K::Open, Lang::En) => "Open", | 205 | (K::Open, Lang::En) => "Open", |
| 212 | (K::Open, Lang::Tr) => "Açık", | 206 | (K::Open, Lang::Tr) => "Açık", |
| 213 | (K::Closed, Lang::En) => "Closed", | 207 | (K::Closed, Lang::En) => "Closed", |
| @@ -442,10 +436,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 442 | (K::FiltersApplied, Lang::Tr) => "Filtreler uygulandı · ", | 436 | (K::FiltersApplied, Lang::Tr) => "Filtreler uygulandı · ", |
| 443 | (K::ClearFilters, Lang::En) => "Clear filters", | 437 | (K::ClearFilters, Lang::En) => "Clear filters", |
| 444 | (K::ClearFilters, Lang::Tr) => "Filtreleri temizle", | 438 | (K::ClearFilters, Lang::Tr) => "Filtreleri temizle", |
| 445 | - (K::Opened, Lang::En) => " opened ", | ||
| 446 | - (K::Opened, Lang::Tr) => " açıldı ", | ||
| 447 | - (K::By, Lang::En) => " by ", | ||
| 448 | - (K::By, Lang::Tr) => " tarafından ", | ||
| 449 | (K::ChooseTemplate, Lang::En) => "Choose a template to start from.", | 439 | (K::ChooseTemplate, Lang::En) => "Choose a template to start from.", |
| 450 | (K::ChooseTemplate, Lang::Tr) => "Başlamak için bir şablon seçin.", | 440 | (K::ChooseTemplate, Lang::Tr) => "Başlamak için bir şablon seçin.", |
| 451 | (K::BlankIssue, Lang::En) => "Open a blank issue", | 441 | (K::BlankIssue, Lang::En) => "Open a blank issue", |
| @@ -545,14 +535,6 @@ pub fn tab_all(lang: Lang, n: impl std::fmt::Display) -> String { | |||
| 545 | } | 535 | } |
| 546 | } | 536 | } |
| 547 | 537 | ||
| 548 | -/// `Page {n}` under the issue list. | ||
| 549 | -pub fn page_label(lang: Lang, n: u32) -> String { | ||
| 550 | - match lang { | ||
| 551 | - Lang::En => format!("Page {n}"), | ||
| 552 | - Lang::Tr => format!("Sayfa {n}"), | ||
| 553 | - } | ||
| 554 | -} | ||
| 555 | - | ||
| 556 | /// `Back to #{n}` on the edit history page. | 538 | /// `Back to #{n}` on the edit history page. |
| 557 | pub fn back_to_item(lang: Lang, number: i64) -> String { | 539 | pub fn back_to_item(lang: Lang, number: i64) -> String { |
| 558 | match lang { | 540 | match lang { |
| @@ -587,44 +569,8 @@ pub fn edit_comment_title(lang: Lang, number: i64, repo: &str) -> String { | |||
| 587 | } | 569 | } |
| 588 | } | 570 | } |
| 589 | 571 | ||
| 590 | -/// `{repo} · Issues`. | 572 | +pub fn repo_title(lang: Lang, repo: &str, key: K) -> String { |
| 591 | -pub fn issues_title(lang: Lang, repo: &str) -> String { | 573 | + format!("{repo} \u{b7} {}", t(lang, key)) |
| 592 | - match lang { | ||
| 593 | - Lang::En => format!("{repo} \u{b7} Issues"), | ||
| 594 | - Lang::Tr => format!("{repo} \u{b7} Sorunlar"), | ||
| 595 | - } | ||
| 596 | -} | ||
| 597 | - | ||
| 598 | -/// `{repo} · New issue`. | ||
| 599 | -pub fn new_issue_title(lang: Lang, repo: &str) -> String { | ||
| 600 | - match lang { | ||
| 601 | - Lang::En => format!("{repo} \u{b7} New issue"), | ||
| 602 | - Lang::Tr => format!("{repo} \u{b7} Yeni sorun"), | ||
| 603 | - } | ||
| 604 | -} | ||
| 605 | - | ||
| 606 | -/// `{repo} · Labels`. | ||
| 607 | -pub fn labels_title(lang: Lang, repo: &str) -> String { | ||
| 608 | - match lang { | ||
| 609 | - Lang::En => format!("{repo} \u{b7} Labels"), | ||
| 610 | - Lang::Tr => format!("{repo} \u{b7} Etiketler"), | ||
| 611 | - } | ||
| 612 | -} | ||
| 613 | - | ||
| 614 | -/// `{repo} · Milestones`. | ||
| 615 | -pub fn milestones_title(lang: Lang, repo: &str) -> String { | ||
| 616 | - match lang { | ||
| 617 | - Lang::En => format!("{repo} \u{b7} Milestones"), | ||
| 618 | - Lang::Tr => format!("{repo} \u{b7} Kilometre taşları"), | ||
| 619 | - } | ||
| 620 | -} | ||
| 621 | - | ||
| 622 | -/// `{repo} · Edit milestone`. | ||
| 623 | -pub fn milestone_edit_title(lang: Lang, repo: &str) -> String { | ||
| 624 | - match lang { | ||
| 625 | - Lang::En => format!("{repo} \u{b7} Edit milestone"), | ||
| 626 | - Lang::Tr => format!("{repo} \u{b7} Kilometre taşını düzenle"), | ||
| 627 | - } | ||
| 628 | } | 574 | } |
| 629 | 575 | ||
| 630 | /// The reader text for the thing whose history is shown: `issue description`, `comment`, ... | 576 | /// The reader text for the thing whose history is shown: `issue description`, `comment`, ... |
| @@ -912,7 +858,6 @@ mod tests { | |||
| 912 | K::Name, | 858 | K::Name, |
| 913 | K::Color, | 859 | K::Color, |
| 914 | K::Reason, | 860 | K::Reason, |
| 915 | - K::None, | ||
| 916 | K::Open, | 861 | K::Open, |
| 917 | K::Closed, | 862 | K::Closed, |
| 918 | K::Search, | 863 | K::Search, |
| @@ -1020,8 +965,6 @@ mod tests { | |||
| 1020 | K::SearchTitles, | 965 | K::SearchTitles, |
| 1021 | K::FiltersApplied, | 966 | K::FiltersApplied, |
| 1022 | K::ClearFilters, | 967 | K::ClearFilters, |
| 1023 | - K::Opened, | ||
| 1024 | - K::By, | ||
| 1025 | K::ChooseTemplate, | 968 | K::ChooseTemplate, |
| 1026 | K::BlankIssue, | 969 | K::BlankIssue, |
| 1027 | K::SubmitNewIssue, | 970 | K::SubmitNewIssue, |
crates/forge-web-base/src/i18n/mod.rsmodified+9 -4
| @@ -10,6 +10,8 @@ | |||
| 10 | //! key modules in `i18n/<group>.rs`, each with its own `K` enum and `t` match, so a group can | 10 | //! key modules in `i18n/<group>.rs`, each with its own `K` enum and `t` match, so a group can |
| 11 | //! be translated without touching the others. | 11 | //! be translated without touching the others. |
| 12 | 12 | ||
| 13 | +use std::fmt::Display; | ||
| 14 | + | ||
| 13 | use http::HeaderMap; | 15 | use http::HeaderMap; |
| 14 | use http::header::ACCEPT_LANGUAGE; | 16 | use http::header::ACCEPT_LANGUAGE; |
| 15 | use topcoat::context::Cx; | 17 | use topcoat::context::Cx; |
| @@ -155,7 +157,6 @@ pub enum Key { | |||
| 155 | Expires, | 157 | Expires, |
| 156 | Upload, | 158 | Upload, |
| 157 | Remove, | 159 | Remove, |
| 158 | - Create, | ||
| 159 | 160 | ||
| 160 | // Log in and two-factor. | 161 | // Log in and two-factor. |
| 161 | TwoFactorCheck, | 162 | TwoFactorCheck, |
| @@ -349,7 +350,6 @@ pub const ALL: &[Key] = &[ | |||
| 349 | Key::Expires, | 350 | Key::Expires, |
| 350 | Key::Upload, | 351 | Key::Upload, |
| 351 | Key::Remove, | 352 | Key::Remove, |
| 352 | - Key::Create, | ||
| 353 | Key::TwoFactorCheck, | 353 | Key::TwoFactorCheck, |
| 354 | Key::ErrInvalidLogin, | 354 | Key::ErrInvalidLogin, |
| 355 | Key::ErrThrottled, | 355 | Key::ErrThrottled, |
| @@ -503,6 +503,13 @@ pub fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { | |||
| 503 | } | 503 | } |
| 504 | } | 504 | } |
| 505 | 505 | ||
| 506 | +pub fn page_label(lang: Lang, page: impl Display) -> String { | ||
| 507 | + match lang { | ||
| 508 | + Lang::En => format!("Page {page}"), | ||
| 509 | + Lang::Tr => format!("Sayfa {page}"), | ||
| 510 | + } | ||
| 511 | +} | ||
| 512 | + | ||
| 506 | pub fn t(lang: Lang, key: Key) -> &'static str { | 513 | pub fn t(lang: Lang, key: Key) -> &'static str { |
| 507 | use Key::*; | 514 | use Key::*; |
| 508 | use Lang::*; | 515 | use Lang::*; |
| @@ -558,8 +565,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 558 | (Upload, Tr) => "Yükle", | 565 | (Upload, Tr) => "Yükle", |
| 559 | (Remove, En) => "Remove", | 566 | (Remove, En) => "Remove", |
| 560 | (Remove, Tr) => "Kaldır", | 567 | (Remove, Tr) => "Kaldır", |
| 561 | - (Create, En) => "Create", | ||
| 562 | - (Create, Tr) => "Oluştur", | ||
| 563 | 568 | ||
| 564 | (TwoFactorCheck, En) => "Two-factor check", | 569 | (TwoFactorCheck, En) => "Two-factor check", |
| 565 | (TwoFactorCheck, Tr) => "İki faktörlü doğrulama", | 570 | (TwoFactorCheck, Tr) => "İki faktörlü doğrulama", |
crates/forge-web-base/src/i18n/pulls.rsmodified+0 -30
| @@ -258,17 +258,6 @@ pub fn viewed_count(lang: Lang, done: usize, total: usize) -> String { | |||
| 258 | } | 258 | } |
| 259 | } | 259 | } |
| 260 | 260 | ||
| 261 | -/// The review bar's pending comment line. | ||
| 262 | -pub fn pending_comments(lang: Lang, count: usize) -> String { | ||
| 263 | - match (lang, count) { | ||
| 264 | - (Lang::En, 0) => "No pending comments.".to_owned(), | ||
| 265 | - (Lang::En, 1) => "1 pending comment.".to_owned(), | ||
| 266 | - (Lang::En, n) => format!("{n} pending comments."), | ||
| 267 | - (Lang::Tr, 0) => "Bekleyen yorum yok.".to_owned(), | ||
| 268 | - (Lang::Tr, n) => format!("{n} bekleyen yorum."), | ||
| 269 | - } | ||
| 270 | -} | ||
| 271 | - | ||
| 272 | /// The "Open N" state tab on the list. | 261 | /// The "Open N" state tab on the list. |
| 273 | pub fn tab_open(lang: Lang, count: impl Display) -> String { | 262 | pub fn tab_open(lang: Lang, count: impl Display) -> String { |
| 274 | match lang { | 263 | match lang { |
| @@ -285,22 +274,6 @@ pub fn tab_closed(lang: Lang, count: impl Display) -> String { | |||
| 285 | } | 274 | } |
| 286 | } | 275 | } |
| 287 | 276 | ||
| 288 | -/// The "All N" state tab on the list. | ||
| 289 | -pub fn tab_all(lang: Lang, count: impl Display) -> String { | ||
| 290 | - match lang { | ||
| 291 | - Lang::En => format!("All {count}"), | ||
| 292 | - Lang::Tr => format!("Tümü {count}"), | ||
| 293 | - } | ||
| 294 | -} | ||
| 295 | - | ||
| 296 | -/// The pager's "Page N" label. | ||
| 297 | -pub fn page_number(lang: Lang, page: impl Display) -> String { | ||
| 298 | - match lang { | ||
| 299 | - Lang::En => format!("Page {page}"), | ||
| 300 | - Lang::Tr => format!("Sayfa {page}"), | ||
| 301 | - } | ||
| 302 | -} | ||
| 303 | - | ||
| 304 | /// The browser title of the pull request list. | 277 | /// The browser title of the pull request list. |
| 305 | pub fn list_title(lang: Lang, owner: &str, repo: &str) -> String { | 278 | pub fn list_title(lang: Lang, owner: &str, repo: &str) -> String { |
| 306 | match lang { | 279 | match lang { |
| @@ -403,11 +376,8 @@ mod tests { | |||
| 403 | assert_eq!(comments(Lang::Tr, 3), "3 yorum"); | 376 | assert_eq!(comments(Lang::Tr, 3), "3 yorum"); |
| 404 | assert_eq!(commit_count(Lang::En, 1), "1 commit"); | 377 | assert_eq!(commit_count(Lang::En, 1), "1 commit"); |
| 405 | assert_eq!(commit_count(Lang::En, 2), "2 commits"); | 378 | assert_eq!(commit_count(Lang::En, 2), "2 commits"); |
| 406 | - assert_eq!(pending_comments(Lang::En, 0), "No pending comments."); | ||
| 407 | - assert_eq!(pending_comments(Lang::Tr, 2), "2 bekleyen yorum."); | ||
| 408 | assert_eq!(tab_open(Lang::En, 2), "Open 2"); | 379 | assert_eq!(tab_open(Lang::En, 2), "Open 2"); |
| 409 | assert_eq!(tab_open(Lang::Tr, 2), "Açık 2"); | 380 | assert_eq!(tab_open(Lang::Tr, 2), "Açık 2"); |
| 410 | - assert_eq!(page_number(Lang::Tr, 4), "Sayfa 4"); | ||
| 411 | assert_eq!(list_title(Lang::En, "a", "b"), "a/b \u{b7} Pull requests"); | 381 | assert_eq!(list_title(Lang::En, "a", "b"), "a/b \u{b7} Pull requests"); |
| 412 | } | 382 | } |
| 413 | } | 383 | } |
crates/forge-web-base/src/i18n/pulls_review.rsmodified+0 -114
| @@ -373,7 +373,6 @@ pub fn branch_deleted(lang: Lang, branch: &str) -> String { | |||
| 373 | } | 373 | } |
| 374 | } | 374 | } |
| 375 | 375 | ||
| 376 | -/// "2 of 3 required approvals". | ||
| 377 | pub fn auto_merge_on(lang: Lang, style: &str, who: &str) -> String { | 376 | pub fn auto_merge_on(lang: Lang, style: &str, who: &str) -> String { |
| 378 | match lang { | 377 | match lang { |
| 379 | Lang::En => format!("Auto-merge is on ({style}), enabled by {who}."), | 378 | Lang::En => format!("Auto-merge is on ({style}), enabled by {who}."), |
| @@ -388,7 +387,6 @@ pub fn approvals_of(lang: Lang, have: impl Display, need: impl Display) -> Strin | |||
| 388 | } | 387 | } |
| 389 | } | 388 | } |
| 390 | 389 | ||
| 391 | -/// "Approved by Ada, Lin". | ||
| 392 | /// Approvals given before the latest push: shown, but no longer counted for the merge rules. | 390 | /// Approvals given before the latest push: shown, but no longer counted for the merge rules. |
| 393 | pub fn approved_before_push(lang: Lang, names: &str) -> String { | 391 | pub fn approved_before_push(lang: Lang, names: &str) -> String { |
| 394 | match lang { | 392 | match lang { |
| @@ -438,122 +436,10 @@ pub fn edit_title(lang: Lang, number: i64, repo: &str) -> String { | |||
| 438 | } | 436 | } |
| 439 | } | 437 | } |
| 440 | 438 | ||
| 441 | -#[cfg(test)] | ||
| 442 | -pub const ALL: &[K] = &[ | ||
| 443 | - K::StateMerged, | ||
| 444 | - K::StateOpen, | ||
| 445 | - K::StateClosed, | ||
| 446 | - K::Unknown, | ||
| 447 | - K::ByWantsToMerge, | ||
| 448 | - K::ByInto, | ||
| 449 | - K::ByFrom, | ||
| 450 | - K::BylineEnd, | ||
| 451 | - K::TabConversation, | ||
| 452 | - K::PullPages, | ||
| 453 | - K::MergeClean, | ||
| 454 | - K::MergeConflict, | ||
| 455 | - K::MergeUpToDate, | ||
| 456 | - K::MergeChecking, | ||
| 457 | - K::MergeStyleLegend, | ||
| 458 | - K::StyleMergeCommit, | ||
| 459 | - K::StyleSquash, | ||
| 460 | - K::StyleFastForward, | ||
| 461 | - K::StyleRebase, | ||
| 462 | - K::ErrDraft, | ||
| 463 | - K::ErrNeedsChecks, | ||
| 464 | - K::ErrRebaseConflict, | ||
| 465 | - K::ErrAutoMergeBlocked, | ||
| 466 | - K::DraftBadge, | ||
| 467 | - K::ReadyForReview, | ||
| 468 | - K::ConvertToDraft, | ||
| 469 | - K::RequiredChecksHeading, | ||
| 470 | - K::CheckPassing, | ||
| 471 | - K::CheckPending, | ||
| 472 | - K::CheckFailing, | ||
| 473 | - K::CheckErrored, | ||
| 474 | - K::CheckMissing, | ||
| 475 | - K::EnableAutoMerge, | ||
| 476 | - K::DisableAutoMerge, | ||
| 477 | - K::MergeMessageLabel, | ||
| 478 | - K::MergeButton, | ||
| 479 | - K::MergedByPrefix, | ||
| 480 | - K::MergedByMiddle, | ||
| 481 | - K::MergedAsSep, | ||
| 482 | - K::DismissButton, | ||
| 483 | - K::ArchivedReadOnly, | ||
| 484 | - K::LoginBefore, | ||
| 485 | - K::LoginLink, | ||
| 486 | - K::LoginAfter, | ||
| 487 | - K::MergedCannotChange, | ||
| 488 | - K::NoCommits, | ||
| 489 | - K::Committed, | ||
| 490 | - K::BrowseFiles, | ||
| 491 | - K::ErrConflict, | ||
| 492 | - K::ErrUpToDate, | ||
| 493 | - K::ErrFfImpossible, | ||
| 494 | - K::ErrBaseMoved, | ||
| 495 | - K::ErrHeadMoved, | ||
| 496 | - K::ErrAlreadyMerged, | ||
| 497 | - K::ErrNotOpen, | ||
| 498 | - K::ErrHeadMissing, | ||
| 499 | - K::ErrBaseMissing, | ||
| 500 | - K::ErrNeedsApprovals, | ||
| 501 | - K::ErrChangesRequested, | ||
| 502 | - K::ErrNotUpToDate, | ||
| 503 | - K::ErrMessageInvalid, | ||
| 504 | - K::ReviewErrStale, | ||
| 505 | - K::ReviewErrOwnPr, | ||
| 506 | - K::ReviewErrEmpty, | ||
| 507 | - K::ReviewErrInvalid, | ||
| 508 | - K::ReviewErrBadLine, | ||
| 509 | - K::ReviewErrClosed, | ||
| 510 | - K::ReviewErrOutdated, | ||
| 511 | - K::ReviewErrNoPush, | ||
| 512 | - K::SuggestedChange, | ||
| 513 | - K::SuggestChange, | ||
| 514 | - K::ApplySuggestion, | ||
| 515 | - K::SuggestionOutdated, | ||
| 516 | - K::EditReviewComment, | ||
| 517 | - K::CommentLabel, | ||
| 518 | - K::SaveComment, | ||
| 519 | - K::CancelButton, | ||
| 520 | - K::Unresolve, | ||
| 521 | - K::Resolve, | ||
| 522 | - K::Outdated, | ||
| 523 | - K::Pending, | ||
| 524 | - K::ReplyLabel, | ||
| 525 | - K::ReplyButton, | ||
| 526 | - K::Edited, | ||
| 527 | - K::EditLink, | ||
| 528 | - K::DeleteButton, | ||
| 529 | -]; | ||
| 530 | - | ||
| 531 | #[cfg(test)] | 439 | #[cfg(test)] |
| 532 | mod tests { | 440 | mod tests { |
| 533 | use super::*; | 441 | use super::*; |
| 534 | 442 | ||
| 535 | - #[test] | ||
| 536 | - fn every_key_has_english_and_turkish() { | ||
| 537 | - for key in ALL { | ||
| 538 | - // The English lead before a login link is empty by design. | ||
| 539 | - if *key != K::LoginBefore { | ||
| 540 | - assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English"); | ||
| 541 | - } | ||
| 542 | - assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish"); | ||
| 543 | - } | ||
| 544 | - } | ||
| 545 | - | ||
| 546 | - #[test] | ||
| 547 | - fn turkish_differs_from_english_for_translated_keys() { | ||
| 548 | - let differing = ALL | ||
| 549 | - .iter() | ||
| 550 | - .filter(|key| t(Lang::En, **key) != t(Lang::Tr, **key)) | ||
| 551 | - .count(); | ||
| 552 | - assert!(differing >= 3, "only {differing} keys differ"); | ||
| 553 | - assert_eq!(t(Lang::En, K::StateOpen), "Open"); | ||
| 554 | - assert_eq!(t(Lang::Tr, K::StateOpen), "Açık"); | ||
| 555 | - } | ||
| 556 | - | ||
| 557 | #[test] | 443 | #[test] |
| 558 | fn counted_helpers_match_english_text() { | 444 | fn counted_helpers_match_english_text() { |
| 559 | assert_eq!(commit_count_line(Lang::En, 1), "1 commit"); | 445 | assert_eq!(commit_count_line(Lang::En, 1), "1 commit"); |
crates/forge-web-base/src/i18n/push.rsmodified+1 -0
| @@ -109,6 +109,7 @@ pub fn last_delivered_label(lang: Lang) -> &'static str { | |||
| 109 | /// "3 new security alerts" for the push about advisories. | 109 | /// "3 new security alerts" for the push about advisories. |
| 110 | pub fn advisory_alerts(lang: Lang, count: u64) -> String { | 110 | pub fn advisory_alerts(lang: Lang, count: u64) -> String { |
| 111 | match lang { | 111 | match lang { |
| 112 | + Lang::En if count == 1 => "1 new security alert".to_owned(), | ||
| 112 | Lang::En => format!("{count} new security alerts"), | 113 | Lang::En => format!("{count} new security alerts"), |
| 113 | Lang::Tr => format!("{count} yeni güvenlik uyarısı"), | 114 | Lang::Tr => format!("{count} yeni güvenlik uyarısı"), |
| 114 | } | 115 | } |
crates/forge-web-base/src/i18n/releases_ci.rsmodified+0 -17
| @@ -127,8 +127,6 @@ pub enum K { | |||
| 127 | NoAssetsYet, | 127 | NoAssetsYet, |
| 128 | NoAssets, | 128 | NoAssets, |
| 129 | File, | 129 | File, |
| 130 | - Size, | ||
| 131 | - Downloads, | ||
| 132 | Edit, | 130 | Edit, |
| 133 | Assets, | 131 | Assets, |
| 134 | AllReleases, | 132 | AllReleases, |
| @@ -397,10 +395,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 397 | (NoAssets, Tr) => "Dosya yok.", | 395 | (NoAssets, Tr) => "Dosya yok.", |
| 398 | (File, En) => "File", | 396 | (File, En) => "File", |
| 399 | (File, Tr) => "Dosya", | 397 | (File, Tr) => "Dosya", |
| 400 | - (Size, En) => "Size", | ||
| 401 | - (Size, Tr) => "Boyut", | ||
| 402 | - (Downloads, En) => "Downloads", | ||
| 403 | - (Downloads, Tr) => "İndirmeler", | ||
| 404 | (Edit, En) => "Edit", | 398 | (Edit, En) => "Edit", |
| 405 | (Edit, Tr) => "Düzenle", | 399 | (Edit, Tr) => "Düzenle", |
| 406 | (Assets, En) => "Assets", | 400 | (Assets, En) => "Assets", |
| @@ -442,14 +436,6 @@ pub fn minutes_only(lang: Lang, m: impl Display) -> String { | |||
| 442 | } | 436 | } |
| 443 | } | 437 | } |
| 444 | 438 | ||
| 445 | -/// "Page 2". | ||
| 446 | -pub fn page_label(lang: Lang, page: u32) -> String { | ||
| 447 | - match lang { | ||
| 448 | - Lang::En => format!("Page {page}"), | ||
| 449 | - Lang::Tr => format!("Sayfa {page}"), | ||
| 450 | - } | ||
| 451 | -} | ||
| 452 | - | ||
| 453 | /// "needs test", for the names of the jobs a job needs. | 439 | /// "needs test", for the names of the jobs a job needs. |
| 454 | pub fn needs_label(lang: Lang, names: &str) -> String { | 440 | pub fn needs_label(lang: Lang, names: &str) -> String { |
| 455 | match lang { | 441 | match lang { |
| @@ -625,8 +611,6 @@ mod tests { | |||
| 625 | K::NoAssetsYet, | 611 | K::NoAssetsYet, |
| 626 | K::NoAssets, | 612 | K::NoAssets, |
| 627 | K::File, | 613 | K::File, |
| 628 | - K::Size, | ||
| 629 | - K::Downloads, | ||
| 630 | K::Edit, | 614 | K::Edit, |
| 631 | K::Assets, | 615 | K::Assets, |
| 632 | K::AllReleases, | 616 | K::AllReleases, |
| @@ -666,6 +650,5 @@ mod tests { | |||
| 666 | assert_eq!(download_count(Lang::En, 1), "1 download"); | 650 | assert_eq!(download_count(Lang::En, 1), "1 download"); |
| 667 | assert_eq!(duration_minutes(Lang::En, 1, 5), "1m 5s"); | 651 | assert_eq!(duration_minutes(Lang::En, 1, 5), "1m 5s"); |
| 668 | assert_eq!(duration_minutes(Lang::Tr, 1, 5), "1 dk 5 sn"); | 652 | assert_eq!(duration_minutes(Lang::Tr, 1, 5), "1 dk 5 sn"); |
| 669 | - assert_eq!(page_label(Lang::Tr, 2), "Sayfa 2"); | ||
| 670 | } | 653 | } |
| 671 | } | 654 | } |
crates/forge-web-base/src/i18n/repo_admin.rsmodified+0 -4
| @@ -76,7 +76,6 @@ pub enum K { | |||
| 76 | RequiredApprovals, | 76 | RequiredApprovals, |
| 77 | RestrictPushTitle, | 77 | RestrictPushTitle, |
| 78 | Role, | 78 | Role, |
| 79 | - Roles, | ||
| 80 | RoleUpdated, | 79 | RoleUpdated, |
| 81 | RequiredChecks, | 80 | RequiredChecks, |
| 82 | RecentContexts, | 81 | RecentContexts, |
| @@ -280,8 +279,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 280 | (Role, En) => "Role", | 279 | (Role, En) => "Role", |
| 281 | (RestrictPushTitle, Tr) => "Yalnızca çekme istekleri üzerinden", | 280 | (RestrictPushTitle, Tr) => "Yalnızca çekme istekleri üzerinden", |
| 282 | (Role, Tr) => "Rol", | 281 | (Role, Tr) => "Rol", |
| 283 | - (Roles, En) => "Roles", | ||
| 284 | - (Roles, Tr) => "Roller", | ||
| 285 | (RoleUpdated, En) => "Role updated.", | 282 | (RoleUpdated, En) => "Role updated.", |
| 286 | (RoleUpdated, Tr) => "Rol güncellendi.", | 283 | (RoleUpdated, Tr) => "Rol güncellendi.", |
| 287 | (RequiredChecks, En) => "Required status checks", | 284 | (RequiredChecks, En) => "Required status checks", |
| @@ -559,7 +556,6 @@ mod tests { | |||
| 559 | K::RequiredApprovals, | 556 | K::RequiredApprovals, |
| 560 | K::RestrictPushTitle, | 557 | K::RestrictPushTitle, |
| 561 | K::Role, | 558 | K::Role, |
| 562 | - K::Roles, | ||
| 563 | K::RoleUpdated, | 559 | K::RoleUpdated, |
| 564 | K::RequiredChecks, | 560 | K::RequiredChecks, |
| 565 | K::RecentContexts, | 561 | K::RecentContexts, |
crates/forge-web-base/src/render/highlight.rsmodified+2 -5
| @@ -5,9 +5,6 @@ | |||
| 5 | //! fragment whose spans are balanced: scopes that continue across a line break | 5 | //! fragment whose spans are balanced: scopes that continue across a line break |
| 6 | //! are closed at the end of the line and reopened at the start of the next. | 6 | //! are closed at the end of the line and reopened at the start of the next. |
| 7 | 7 | ||
| 8 | -// Nothing outside the tests calls this module until the blob view is wired up. | ||
| 9 | -#![allow(dead_code)] | ||
| 10 | - | ||
| 11 | use std::sync::LazyLock; | 8 | use std::sync::LazyLock; |
| 12 | 9 | ||
| 13 | use syntect::highlighting::ThemeSet; | 10 | use syntect::highlighting::ThemeSet; |
| @@ -214,8 +211,8 @@ fn scope_css(css: &str, scope: &str) -> String { | |||
| 214 | } | 211 | } |
| 215 | 212 | ||
| 216 | /// CSS for the `hl-` classes: both themes, each scoped to the page theme it belongs to. | 213 | /// CSS for the `hl-` classes: both themes, each scoped to the page theme it belongs to. |
| 217 | -pub fn highlight_css() -> String { | 214 | +pub fn highlight_css() -> &'static str { |
| 218 | - CSS.clone() | 215 | + CSS.as_str() |
| 219 | } | 216 | } |
| 220 | 217 | ||
| 221 | #[cfg(test)] | 218 | #[cfg(test)] |
crates/forge-web-base/src/render/markdown.rsmodified+4 -15
| @@ -80,7 +80,6 @@ fn markdown_options() -> Options<'static> { | |||
| 80 | options.extension.alerts = true; | 80 | options.extension.alerts = true; |
| 81 | options.extension.math_dollars = true; | 81 | options.extension.math_dollars = true; |
| 82 | options.extension.header_id_prefix = Some(ID_PREFIX.to_string()); | 82 | options.extension.header_id_prefix = Some(ID_PREFIX.to_string()); |
| 83 | - // Raw HTML is passed through to ammonia, which removes anything not allowlisted. | ||
| 84 | options.render.r#unsafe = true; | 83 | options.render.r#unsafe = true; |
| 85 | options | 84 | options |
| 86 | } | 85 | } |
| @@ -109,15 +108,11 @@ impl Resolver { | |||
| 109 | fn new(ctx: &LinkContext) -> Self { | 108 | fn new(ctx: &LinkContext) -> Self { |
| 110 | let blob = ctx.blob_base.trim_end_matches('/'); | 109 | let blob = ctx.blob_base.trim_end_matches('/'); |
| 111 | let depth = dir_depth(blob); | 110 | let depth = dir_depth(blob); |
| 112 | - let dir = blob | 111 | + let segments: Vec<&str> = blob.split('/').collect(); |
| 113 | - .split('/') | 112 | + let dir: Vec<String> = segments[segments.len() - depth..] |
| 114 | - .rev() | 113 | + .iter() |
| 115 | - .take(depth) | ||
| 116 | .filter(|seg| !seg.is_empty()) | 114 | .filter(|seg| !seg.is_empty()) |
| 117 | - .map(str::to_string) | 115 | + .map(|s| s.to_string()) |
| 118 | - .collect::<Vec<_>>() | ||
| 119 | - .into_iter() | ||
| 120 | - .rev() | ||
| 121 | .collect(); | 116 | .collect(); |
| 122 | Self { | 117 | Self { |
| 123 | tree_root: strip_segments(&ctx.tree_base, depth), | 118 | tree_root: strip_segments(&ctx.tree_base, depth), |
| @@ -129,7 +124,6 @@ impl Resolver { | |||
| 129 | 124 | ||
| 130 | /// Returns the rewritten URL, or `None` to keep the original. | 125 | /// Returns the rewritten URL, or `None` to keep the original. |
| 131 | fn rewrite(&self, url: &str, image: bool) -> Option<String> { | 126 | fn rewrite(&self, url: &str, image: bool) -> Option<String> { |
| 132 | - // Attachment URLs are site-absolute and independent of the rendered file's location. | ||
| 133 | if url.is_empty() | 127 | if url.is_empty() |
| 134 | || url.starts_with("//") | 128 | || url.starts_with("//") |
| 135 | || has_scheme(url) | 129 | || has_scheme(url) |
| @@ -327,8 +321,6 @@ fn link_refs<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>, issues_base: &str) | |||
| 327 | children.push(new_node(arena, sourcepos, NodeValue::HtmlInline(html))) | 321 | children.push(new_node(arena, sourcepos, NodeValue::HtmlInline(html))) |
| 328 | } | 322 | } |
| 329 | HtmlPiece::Text(raw) => { | 323 | HtmlPiece::Text(raw) => { |
| 330 | - // Raw text may hold entities; comrak escapes Text nodes again, so decode | ||
| 331 | - // them first. | ||
| 332 | let text = decode_entities(&raw); | 324 | let text = decode_entities(&raw); |
| 333 | match text_with_links(arena, sourcepos, &text, issues_base) { | 325 | match text_with_links(arena, sourcepos, &text, issues_base) { |
| 334 | Some(nodes) => { | 326 | Some(nodes) => { |
| @@ -344,7 +336,6 @@ fn link_refs<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>, issues_base: &str) | |||
| 344 | } | 336 | } |
| 345 | } | 337 | } |
| 346 | } | 338 | } |
| 347 | - // Only rewrite the block when something was actually linked. | ||
| 348 | if linked { | 339 | if linked { |
| 349 | node.data.borrow_mut().value = NodeValue::Paragraph; | 340 | node.data.borrow_mut().value = NodeValue::Paragraph; |
| 350 | for child in children { | 341 | for child in children { |
| @@ -885,7 +876,6 @@ mod tests { | |||
| 885 | true, | 876 | true, |
| 886 | &["src=\"https://raw.test/o/r/main/img.png\""], | 877 | &["src=\"https://raw.test/o/r/main/img.png\""], |
| 887 | ), | 878 | ), |
| 888 | - // The fragment belongs to the target file (e.g. #L12 on code), so it is left as is. | ||
| 889 | ( | 879 | ( |
| 890 | "[r](/README.md#top) [s](/a/../b.md)", | 880 | "[r](/README.md#top) [s](/a/../b.md)", |
| 891 | true, | 881 | true, |
| @@ -1008,7 +998,6 @@ mod tests { | |||
| 1008 | "`#12` and @bob\n\n```\n#13 @carol\n```\n", | 998 | "`#12` and @bob\n\n```\n#13 @carol\n```\n", |
| 1009 | Some(&issue_ctx()), | 999 | Some(&issue_ctx()), |
| 1010 | ); | 1000 | ); |
| 1011 | - // `@bob` is plain text and is linked; the refs inside code are not. | ||
| 1012 | assert!(!html.contains("issue-ref"), "{html}"); | 1001 | assert!(!html.contains("issue-ref"), "{html}"); |
| 1013 | assert_eq!(html.matches("user-mention").count(), 1, "{html}"); | 1002 | assert_eq!(html.matches("user-mention").count(), 1, "{html}"); |
| 1014 | assert!(html.contains(">@bob</a>"), "{html}"); | 1003 | assert!(html.contains(">@bob</a>"), "{html}"); |
crates/forge-web-base/src/repo_stats.rsmodified+0 -31
| @@ -1,23 +1,14 @@ | |||
| 1 | -//! Repo statistics from a tree listing: the language shares shown on a repo page, and the license | ||
| 2 | -//! a root file holds. These are pure functions over paths, sizes and text, so the caller does the | ||
| 3 | -//! git reads. | ||
| 4 | - | ||
| 5 | use std::collections::BTreeMap; | 1 | use std::collections::BTreeMap; |
| 6 | 2 | ||
| 7 | -/// One language's share of the tree. | ||
| 8 | #[derive(Clone, Debug, PartialEq, Eq)] | 3 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 9 | pub struct LangShare { | 4 | pub struct LangShare { |
| 10 | - /// "Rust", or "Other" for the remainder row. | ||
| 11 | pub name: String, | 5 | pub name: String, |
| 12 | pub files: u64, | 6 | pub files: u64, |
| 13 | pub bytes: u64, | 7 | pub bytes: u64, |
| 14 | - /// Rounded, 0..=100. The shares sum to 100 when there is any code. | ||
| 15 | pub percent: u32, | 8 | pub percent: u32, |
| 16 | - /// Only on the "Other" row: the names of the languages folded into it, biggest first. | ||
| 17 | pub others: Vec<String>, | 9 | pub others: Vec<String>, |
| 18 | } | 10 | } |
| 19 | 11 | ||
| 20 | -/// Extensions (lowercase, without the dot) and the language each one counts as. | ||
| 21 | const EXTENSIONS: &[(&str, &str)] = &[ | 12 | const EXTENSIONS: &[(&str, &str)] = &[ |
| 22 | ("rs", "Rust"), | 13 | ("rs", "Rust"), |
| 23 | ("js", "JavaScript"), | 14 | ("js", "JavaScript"), |
| @@ -108,7 +99,6 @@ const EXTENSIONS: &[(&str, &str)] = &[ | |||
| 108 | ("odin", "Odin"), | 99 | ("odin", "Odin"), |
| 109 | ]; | 100 | ]; |
| 110 | 101 | ||
| 111 | -/// Directory names whose contents are vendored or built, so they never count. | ||
| 112 | const SKIPPED_SEGMENTS: &[&str] = &[ | 102 | const SKIPPED_SEGMENTS: &[&str] = &[ |
| 113 | "vendor", | 103 | "vendor", |
| 114 | "node_modules", | 104 | "node_modules", |
| @@ -118,8 +108,6 @@ const SKIPPED_SEGMENTS: &[&str] = &[ | |||
| 118 | ".git", | 108 | ".git", |
| 119 | ]; | 109 | ]; |
| 120 | 110 | ||
| 121 | -/// The language a path counts as, by its exact file name or its extension. None for anything | ||
| 122 | -/// unknown, vendored, generated or prose. | ||
| 123 | fn language_of(path: &str) -> Option<&'static str> { | 111 | fn language_of(path: &str) -> Option<&'static str> { |
| 124 | if path.split('/').any(|seg| SKIPPED_SEGMENTS.contains(&seg)) { | 112 | if path.split('/').any(|seg| SKIPPED_SEGMENTS.contains(&seg)) { |
| 125 | return None; | 113 | return None; |
| @@ -149,9 +137,6 @@ fn language_of(path: &str) -> Option<&'static str> { | |||
| 149 | .map(|(_, lang)| *lang) | 137 | .map(|(_, lang)| *lang) |
| 150 | } | 138 | } |
| 151 | 139 | ||
| 152 | -/// The languages of a tree from `(path, size)` pairs, biggest first: the top `top` languages, then | ||
| 153 | -/// one "Other" row folding the rest (left out when nothing is folded). Unknown files, vendored or | ||
| 154 | -/// generated paths and prose do not count. | ||
| 155 | pub fn languages(files: &[(String, u64)], top: usize) -> Vec<LangShare> { | 140 | pub fn languages(files: &[(String, u64)], top: usize) -> Vec<LangShare> { |
| 156 | let mut by_lang: BTreeMap<&'static str, (u64, u64)> = BTreeMap::new(); | 141 | let mut by_lang: BTreeMap<&'static str, (u64, u64)> = BTreeMap::new(); |
| 157 | for (path, size) in files { | 142 | for (path, size) in files { |
| @@ -171,7 +156,6 @@ pub fn languages(files: &[(String, u64)], top: usize) -> Vec<LangShare> { | |||
| 171 | others: Vec::new(), | 156 | others: Vec::new(), |
| 172 | }) | 157 | }) |
| 173 | .collect(); | 158 | .collect(); |
| 174 | - // Biggest first; equal sizes keep their name order, which the BTreeMap gave. | ||
| 175 | rows.sort_by_key(|a| std::cmp::Reverse(a.bytes)); | 159 | rows.sort_by_key(|a| std::cmp::Reverse(a.bytes)); |
| 176 | 160 | ||
| 177 | if rows.len() > top { | 161 | if rows.len() > top { |
| @@ -190,8 +174,6 @@ pub fn languages(files: &[(String, u64)], top: usize) -> Vec<LangShare> { | |||
| 190 | rows | 174 | rows |
| 191 | } | 175 | } |
| 192 | 176 | ||
| 193 | -/// Sets each row's percent from its bytes by largest remainder, so the rounded shares sum to 100. | ||
| 194 | -/// Leaves every percent at 0 when there are no bytes. | ||
| 195 | fn assign_percents(rows: &mut [LangShare], total: u64) { | 177 | fn assign_percents(rows: &mut [LangShare], total: u64) { |
| 196 | if total == 0 { | 178 | if total == 0 { |
| 197 | return; | 179 | return; |
| @@ -212,9 +194,6 @@ fn assign_percents(rows: &mut [LangShare], total: u64) { | |||
| 212 | } | 194 | } |
| 213 | } | 195 | } |
| 214 | 196 | ||
| 215 | -/// The SPDX id a license text matches, such as "MIT", "Apache-2.0", "GPL-3.0", "AGPL-3.0", | ||
| 216 | -/// "LGPL-3.0", "MPL-2.0", "BSD-3-Clause", "BSD-2-Clause", "ISC", "Unlicense", "GPL-2.0", | ||
| 217 | -/// "LGPL-2.1", "BSL-1.0", "0BSD". None when it matches none. | ||
| 218 | pub fn license_id(text: &str) -> Option<&'static str> { | 197 | pub fn license_id(text: &str) -> Option<&'static str> { |
| 219 | let t = normalise(text); | 198 | let t = normalise(text); |
| 220 | if t.contains("permission is hereby granted, free of charge") { | 199 | if t.contains("permission is hereby granted, free of charge") { |
| @@ -233,7 +212,6 @@ pub fn license_id(text: &str) -> Option<&'static str> { | |||
| 233 | return Some("MPL-2.0"); | 212 | return Some("MPL-2.0"); |
| 234 | } | 213 | } |
| 235 | if t.contains("permission to use, copy, modify, and/or distribute this software for any purpose with or without fee") { | 214 | if t.contains("permission to use, copy, modify, and/or distribute this software for any purpose with or without fee") { |
| 236 | - // The ISC text adds the copyright notice requirement that 0BSD drops. | ||
| 237 | return Some(if t.contains("provided that the above copyright notice") { | 215 | return Some(if t.contains("provided that the above copyright notice") { |
| 238 | "ISC" | 216 | "ISC" |
| 239 | } else { | 217 | } else { |
| @@ -250,8 +228,6 @@ pub fn license_id(text: &str) -> Option<&'static str> { | |||
| 250 | copyleft_id(&t) | 228 | copyleft_id(&t) |
| 251 | } | 229 | } |
| 252 | 230 | ||
| 253 | -/// The GPL family id for normalised (lowercase, single-spaced) text. The title that comes first | ||
| 254 | -/// in the text is the license's own: a GPL text names the LGPL later on. | ||
| 255 | fn copyleft_id(t: &str) -> Option<&'static str> { | 231 | fn copyleft_id(t: &str) -> Option<&'static str> { |
| 256 | const TITLES: [(&str, &str); 3] = [ | 232 | const TITLES: [(&str, &str); 3] = [ |
| 257 | ("gnu affero general public license", "AGPL"), | 233 | ("gnu affero general public license", "AGPL"), |
| @@ -262,7 +238,6 @@ fn copyleft_id(t: &str) -> Option<&'static str> { | |||
| 262 | .iter() | 238 | .iter() |
| 263 | .filter_map(|(title, family)| t.find(title).map(|pos| (pos, *title, *family))) | 239 | .filter_map(|(title, family)| t.find(title).map(|pos| (pos, *title, *family))) |
| 264 | .min_by_key(|(pos, _, _)| *pos)?; | 240 | .min_by_key(|(pos, _, _)| *pos)?; |
| 265 | - // The version follows the title, as in "Version 3, 29 June 2007". | ||
| 266 | let after: String = t[pos + title.len()..].chars().take(40).collect(); | 241 | let after: String = t[pos + title.len()..].chars().take(40).collect(); |
| 267 | let version = if after.contains("version 2.1") { | 242 | let version = if after.contains("version 2.1") { |
| 268 | "2.1" | 243 | "2.1" |
| @@ -283,8 +258,6 @@ fn copyleft_id(t: &str) -> Option<&'static str> { | |||
| 283 | } | 258 | } |
| 284 | } | 259 | } |
| 285 | 260 | ||
| 286 | -/// Lowercases the text and collapses every run of whitespace, so line wrapping does not split a | ||
| 287 | -/// phrase. | ||
| 288 | fn normalise(text: &str) -> String { | 261 | fn normalise(text: &str) -> String { |
| 289 | text.split_whitespace() | 262 | text.split_whitespace() |
| 290 | .collect::<Vec<_>>() | 263 | .collect::<Vec<_>>() |
| @@ -292,7 +265,6 @@ fn normalise(text: &str) -> String { | |||
| 292 | .to_lowercase() | 265 | .to_lowercase() |
| 293 | } | 266 | } |
| 294 | 267 | ||
| 295 | -/// File names that hold a license at the repo root, in preference order (lowercase). | ||
| 296 | const LICENSE_NAMES: &[&str] = &[ | 268 | const LICENSE_NAMES: &[&str] = &[ |
| 297 | "license", | 269 | "license", |
| 298 | "license.md", | 270 | "license.md", |
| @@ -311,8 +283,6 @@ const LICENSE_NAMES: &[&str] = &[ | |||
| 311 | "license-gpl", | 283 | "license-gpl", |
| 312 | ]; | 284 | ]; |
| 313 | 285 | ||
| 314 | -/// The root entry that holds the license, if any: LICENSE, LICENSE.md, LICENSE.txt, LICENCE, | ||
| 315 | -/// COPYING, LICENSE-MIT ... (case-insensitive). The first match in a fixed preference order. | ||
| 316 | pub fn license_file(root_names: &[String]) -> Option<&str> { | 286 | pub fn license_file(root_names: &[String]) -> Option<&str> { |
| 317 | LICENSE_NAMES.iter().find_map(|want| { | 287 | LICENSE_NAMES.iter().find_map(|want| { |
| 318 | root_names | 288 | root_names |
| @@ -359,7 +329,6 @@ mod tests { | |||
| 359 | let mit = "MIT License\n\nCopyright (c) 2026 Someone\n\nPermission is hereby granted, free of\ncharge, to any person obtaining a copy"; | 329 | let mit = "MIT License\n\nCopyright (c) 2026 Someone\n\nPermission is hereby granted, free of\ncharge, to any person obtaining a copy"; |
| 360 | assert_eq!(license_id(mit), Some("MIT")); | 330 | assert_eq!(license_id(mit), Some("MIT")); |
| 361 | 331 | ||
| 362 | - // The AGPL text also names the GPL later on, which must not win. | ||
| 363 | let agpl = " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n ... version 3 of the GNU General Public License ..."; | 332 | let agpl = " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n ... version 3 of the GNU General Public License ..."; |
| 364 | assert_eq!(license_id(agpl), Some("AGPL-3.0")); | 333 | assert_eq!(license_id(agpl), Some("AGPL-3.0")); |
| 365 | } | 334 | } |
crates/forge-web-base/src/theme.rsmodified+46 -54
| @@ -3,22 +3,46 @@ | |||
| 3 | //! visitor with no explicit choice gets light whatever their operating system uses. Only an | 3 | //! visitor with no explicit choice gets light whatever their operating system uses. Only an |
| 4 | //! explicit `auto` renders no `data-theme`, so the stylesheet follows the operating system. | 4 | //! explicit `auto` renders no `data-theme`, so the stylesheet follows the operating system. |
| 5 | 5 | ||
| 6 | -use std::time::Duration; | ||
| 7 | - | ||
| 8 | use forge_core::User; | 6 | use forge_core::User; |
| 9 | use topcoat::context::Cx; | 7 | use topcoat::context::Cx; |
| 10 | use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; | 8 | use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; |
| 11 | 9 | ||
| 12 | -/// Name of the anonymous theme cookie. | 10 | +const THEME_COOKIE: &str = "forge_theme"; |
| 13 | -pub const THEME_COOKIE: &str = "forge_theme"; | 11 | + |
| 12 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 13 | +pub enum Theme { | ||
| 14 | + Light, | ||
| 15 | + Dark, | ||
| 16 | + Auto, | ||
| 17 | +} | ||
| 14 | 18 | ||
| 15 | -/// Lifetime of the anonymous theme cookie. | 19 | +impl Theme { |
| 16 | -pub const THEME_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60); | 20 | + pub fn from_stored(stored: &str) -> Self { |
| 21 | + match stored { | ||
| 22 | + "auto" => Self::Auto, | ||
| 23 | + "dark" => Self::Dark, | ||
| 24 | + _ => Self::Light, | ||
| 25 | + } | ||
| 26 | + } | ||
| 17 | 27 | ||
| 18 | -/// The stored colour preference for this request: `"auto"`, `"light"` or `"dark"`. A signed-in | 28 | + pub fn as_str(self) -> &'static str { |
| 19 | -/// user's stored preference wins. Anonymous visitors use the cookie. A missing, empty or | 29 | + match self { |
| 20 | -/// unknown value reads as `"light"`, the default. Only an explicit `"auto"` follows the system. | 30 | + Self::Light => "light", |
| 21 | -pub fn preference(cx: &Cx, viewer: Option<&User>) -> &'static str { | 31 | + Self::Dark => "dark", |
| 32 | + Self::Auto => "auto", | ||
| 33 | + } | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + pub fn next(self) -> Self { | ||
| 37 | + match self { | ||
| 38 | + Self::Light => Self::Dark, | ||
| 39 | + Self::Dark => Self::Auto, | ||
| 40 | + Self::Auto => Self::Light, | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +pub fn preference(cx: &Cx, viewer: Option<&User>) -> Theme { | ||
| 22 | let stored = match viewer { | 46 | let stored = match viewer { |
| 23 | Some(user) => user.theme.clone(), | 47 | Some(user) => user.theme.clone(), |
| 24 | None => cookies(cx) | 48 | None => cookies(cx) |
| @@ -26,77 +50,45 @@ pub fn preference(cx: &Cx, viewer: Option<&User>) -> &'static str { | |||
| 26 | .map(|cookie| cookie.value().to_owned()) | 50 | .map(|cookie| cookie.value().to_owned()) |
| 27 | .unwrap_or_default(), | 51 | .unwrap_or_default(), |
| 28 | }; | 52 | }; |
| 29 | - resolve_preference(&stored) | 53 | + Theme::from_stored(&stored) |
| 30 | } | 54 | } |
| 31 | 55 | ||
| 32 | -/// Maps a stored value to a preference. Only `"auto"` and `"dark"` are kept as they are. Every | ||
| 33 | -/// other value, including the empty string, means the default, `"light"`. | ||
| 34 | -pub fn resolve_preference(stored: &str) -> &'static str { | ||
| 35 | - match stored { | ||
| 36 | - "auto" => "auto", | ||
| 37 | - "dark" => "dark", | ||
| 38 | - _ => "light", | ||
| 39 | - } | ||
| 40 | -} | ||
| 41 | - | ||
| 42 | -/// The `data-theme` value for this request: `Some("light")` or `Some("dark")`, or `None` when the | ||
| 43 | -/// page should follow the operating system. | ||
| 44 | pub fn data_theme(cx: &Cx, viewer: Option<&User>) -> Option<&'static str> { | 56 | pub fn data_theme(cx: &Cx, viewer: Option<&User>) -> Option<&'static str> { |
| 45 | match preference(cx, viewer) { | 57 | match preference(cx, viewer) { |
| 46 | - "auto" => None, | 58 | + Theme::Auto => None, |
| 47 | - theme => Some(theme), | 59 | + theme => Some(theme.as_str()), |
| 48 | - } | ||
| 49 | -} | ||
| 50 | - | ||
| 51 | -/// The preference the top-bar button switches to from `current`: light, then dark, then auto, | ||
| 52 | -/// then back to light. Anything that is not `"light"` or `"dark"` (including `"auto"`) moves on | ||
| 53 | -/// to light, the first step of the cycle. | ||
| 54 | -pub fn next_preference(current: &str) -> &'static str { | ||
| 55 | - match current { | ||
| 56 | - "light" => "dark", | ||
| 57 | - "dark" => "auto", | ||
| 58 | - _ => "light", | ||
| 59 | } | 60 | } |
| 60 | } | 61 | } |
| 61 | 62 | ||
| 62 | -/// Sets the anonymous theme cookie. The caller has already checked that `theme` is valid. | ||
| 63 | pub fn set_theme_cookie(cx: &Cx, theme: &str) { | 63 | pub fn set_theme_cookie(cx: &Cx, theme: &str) { |
| 64 | - let max_age = | ||
| 65 | - time::Duration::seconds(i64::try_from(THEME_COOKIE_TTL.as_secs()).unwrap_or(i64::MAX)); | ||
| 66 | cookies(cx).add( | 64 | cookies(cx).add( |
| 67 | Cookie::build((THEME_COOKIE, theme.to_owned())) | 65 | Cookie::build((THEME_COOKIE, theme.to_owned())) |
| 68 | .path("/") | 66 | .path("/") |
| 69 | .secure(true) | 67 | .secure(true) |
| 70 | .http_only(true) | 68 | .http_only(true) |
| 71 | .same_site(SameSite::Lax) | 69 | .same_site(SameSite::Lax) |
| 72 | - .max_age(max_age) | 70 | + .max_age(time::Duration::days(365)) |
| 73 | .build(), | 71 | .build(), |
| 74 | ); | 72 | ); |
| 75 | } | 73 | } |
| 76 | 74 | ||
| 77 | #[cfg(test)] | 75 | #[cfg(test)] |
| 78 | mod tests { | 76 | mod tests { |
| 79 | - use super::{next_preference, resolve_preference}; | 77 | + use super::Theme; |
| 80 | 78 | ||
| 81 | #[test] | 79 | #[test] |
| 82 | fn the_toggle_cycles_light_dark_auto_light() { | 80 | fn the_toggle_cycles_light_dark_auto_light() { |
| 83 | - assert_eq!(next_preference("light"), "dark"); | 81 | + assert_eq!(Theme::Light.next(), Theme::Dark); |
| 84 | - assert_eq!(next_preference("dark"), "auto"); | 82 | + assert_eq!(Theme::Dark.next(), Theme::Auto); |
| 85 | - assert_eq!(next_preference("auto"), "light"); | 83 | + assert_eq!(Theme::Auto.next(), Theme::Light); |
| 86 | } | 84 | } |
| 87 | 85 | ||
| 88 | #[test] | 86 | #[test] |
| 89 | fn unknown_or_missing_preferences_fall_back_to_light() { | 87 | fn unknown_or_missing_preferences_fall_back_to_light() { |
| 90 | - for pref in ["", "neon"] { | 88 | + for stored in ["", "neon", "light"] { |
| 91 | - assert_eq!(next_preference(pref), "light", "next {pref:?}"); | 89 | + assert_eq!(Theme::from_stored(stored), Theme::Light, "{stored:?}"); |
| 92 | - assert_eq!(resolve_preference(pref), "light", "resolve {pref:?}"); | ||
| 93 | } | 90 | } |
| 94 | - assert_eq!(resolve_preference("light"), "light"); | 91 | + assert_eq!(Theme::from_stored("dark"), Theme::Dark); |
| 95 | - } | 92 | + assert_eq!(Theme::from_stored("auto"), Theme::Auto); |
| 96 | - | ||
| 97 | - #[test] | ||
| 98 | - fn explicit_choices_are_kept() { | ||
| 99 | - assert_eq!(resolve_preference("dark"), "dark"); | ||
| 100 | - assert_eq!(resolve_preference("auto"), "auto"); | ||
| 101 | } | 93 | } |
| 102 | } | 94 | } |
crates/forge-web-base/src/throttle.rsmodified+21 -11
| @@ -3,7 +3,8 @@ | |||
| 3 | //! Each key keeps the timestamps of its recent failures. A key is limited while it has `limit` | 3 | //! Each key keeps the timestamps of its recent failures. A key is limited while it has `limit` |
| 4 | //! failures inside the window. Failures are only recorded for rejected credentials, so a locked | 4 | //! failures inside the window. Failures are only recorded for rejected credentials, so a locked |
| 5 | //! key stops growing. Memory stays bounded: expired timestamps and empty keys are pruned | 5 | //! key stops growing. Memory stays bounded: expired timestamps and empty keys are pruned |
| 6 | -//! periodically, and when the key cap is reached the key with the oldest failure is evicted. | 6 | +//! periodically, and when the key cap is reached the key with the fewest failures is evicted, so a |
| 7 | +//! flood of one-failure keys cannot lift a key that is locked. | ||
| 7 | 8 | ||
| 8 | use std::collections::{HashMap, VecDeque}; | 9 | use std::collections::{HashMap, VecDeque}; |
| 9 | use std::net::IpAddr; | 10 | use std::net::IpAddr; |
| @@ -74,7 +75,7 @@ impl Throttle { | |||
| 74 | self.prune_locked(&mut state, now); | 75 | self.prune_locked(&mut state, now); |
| 75 | } | 76 | } |
| 76 | if !state.failures.contains_key(key) && state.failures.len() >= self.max_keys { | 77 | if !state.failures.contains_key(key) && state.failures.len() >= self.max_keys { |
| 77 | - self.evict_oldest_locked(&mut state); | 78 | + self.evict_least_failing_locked(&mut state); |
| 78 | } | 79 | } |
| 79 | let timestamps = state.failures.entry(key.to_owned()).or_default(); | 80 | let timestamps = state.failures.entry(key.to_owned()).or_default(); |
| 80 | drop_expired(timestamps, self.window, now); | 81 | drop_expired(timestamps, self.window, now); |
| @@ -107,14 +108,17 @@ impl Throttle { | |||
| 107 | }); | 108 | }); |
| 108 | } | 109 | } |
| 109 | 110 | ||
| 110 | - /// Removes the key whose most recent failure is the oldest. Runs only when the cap is hit. | 111 | + /// Removes the key with the fewest failures, the oldest last failure first on ties. |
| 111 | - fn evict_oldest_locked(&self, state: &mut State) { | 112 | + /// Runs only when the cap is hit. |
| 113 | + fn evict_least_failing_locked(&self, state: &mut State) { | ||
| 112 | let victim = state | 114 | let victim = state |
| 113 | .failures | 115 | .failures |
| 114 | .iter() | 116 | .iter() |
| 115 | - .filter_map(|(key, timestamps)| timestamps.back().map(|last| (key, *last))) | 117 | + .filter_map(|(key, timestamps)| { |
| 116 | - .min_by_key(|(_, last)| *last) | 118 | + timestamps.back().map(|last| (key, timestamps.len(), *last)) |
| 117 | - .map(|(key, _)| key.clone()); | 119 | + }) |
| 120 | + .min_by_key(|(_, count, last)| (*count, *last)) | ||
| 121 | + .map(|(key, _, _)| key.clone()); | ||
| 118 | if let Some(key) = victim { | 122 | if let Some(key) = victim { |
| 119 | state.failures.remove(&key); | 123 | state.failures.remove(&key); |
| 120 | } | 124 | } |
| @@ -217,9 +221,15 @@ mod tests { | |||
| 217 | } | 221 | } |
| 218 | 222 | ||
| 219 | #[test] | 223 | #[test] |
| 220 | - fn keys_are_scoped_by_ip() { | 224 | + fn flood_does_not_evict_a_locked_key() { |
| 221 | - let ip: IpAddr = "192.0.2.1".parse().unwrap(); | 225 | + let throttle = Throttle::with_limits(Duration::from_secs(60), 4); |
| 222 | - assert_eq!(ip_key("git-ip", ip), "git-ip:192.0.2.1"); | 226 | + let t0 = base(); |
| 223 | - assert_eq!(user_key("tahinli"), "user:tahinli"); | 227 | + for _ in 0..3 { |
| 228 | + throttle.record_failure("locked", t0); | ||
| 229 | + } | ||
| 230 | + for i in 0..10u64 { | ||
| 231 | + throttle.record_failure(&format!("fresh-{i}"), t0 + Duration::from_millis(i)); | ||
| 232 | + } | ||
| 233 | + assert!(throttle.check("locked", 3, t0).is_some()); | ||
| 224 | } | 234 | } |
| 225 | } | 235 | } |
crates/forge-web-pages/src/pages/ci_runs.rsmodified+1 -1
| @@ -1795,7 +1795,7 @@ async fn runs_split( | |||
| 1795 | rows, | 1795 | rows, |
| 1796 | newer_href, | 1796 | newer_href, |
| 1797 | older_href, | 1797 | older_href, |
| 1798 | - page_label: g::page_label(lang, page), | 1798 | + page_label: i18n::page_label(lang, page), |
| 1799 | next_scheduled: { | 1799 | next_scheduled: { |
| 1800 | let schedules = crate::ci::schedule::schedules_of(state, &ctx.repo).await; | 1800 | let schedules = crate::ci::schedule::schedules_of(state, &ctx.repo).await; |
| 1801 | forge_ci::cron::next_after(&schedules, now).and_then(next_run_text) | 1801 | forge_ci::cron::next_after(&schedules, now).and_then(next_run_text) |
crates/forge-web-pages/src/pages/finder.rsmodified+1 -1
| @@ -44,7 +44,7 @@ pub async fn file_finder( | |||
| 44 | <dialog class="finder" data-finder="" data-src=(src.as_str()) data-base=(base.as_str()) | 44 | <dialog class="finder" data-finder="" data-src=(src.as_str()) data-base=(base.as_str()) |
| 45 | data-loading=(b::t(lang, b::K::FinderLoading)) data-empty=(b::t(lang, b::K::FinderEmpty)) | 45 | data-loading=(b::t(lang, b::K::FinderLoading)) data-empty=(b::t(lang, b::K::FinderEmpty)) |
| 46 | data-failed=(b::t(lang, b::K::FinderFailed)) data-truncated=(b::t(lang, b::K::FinderTruncated)) | 46 | data-failed=(b::t(lang, b::K::FinderFailed)) data-truncated=(b::t(lang, b::K::FinderTruncated)) |
| 47 | - aria-label=(b::t(lang, b::K::FinderTitle))> | 47 | + aria-label=(b::t(lang, b::K::GoToFile))> |
| 48 | <div class="finder-box"> | 48 | <div class="finder-box"> |
| 49 | <input type="text" class="finder-input" data-finder-input="" autocomplete="off" spellcheck="false" | 49 | <input type="text" class="finder-input" data-finder-input="" autocomplete="off" spellcheck="false" |
| 50 | placeholder=(b::t(lang, b::K::FinderPlaceholder)) aria-label=(b::t(lang, b::K::FinderPlaceholder)) | 50 | placeholder=(b::t(lang, b::K::FinderPlaceholder)) aria-label=(b::t(lang, b::K::FinderPlaceholder)) |
crates/forge-web-pages/src/pages/issues_list.rsmodified+12 -5
| @@ -486,7 +486,7 @@ async fn issues_list_page(cx: &Cx) -> Result<impl View> { | |||
| 486 | let has_older = u64::from(sel.page) < last_page; | 486 | let has_older = u64::from(sel.page) < last_page; |
| 487 | let newer_href = sel.href(&base, sel.state, sel.page.saturating_sub(1)); | 487 | let newer_href = sel.href(&base, sel.state, sel.page.saturating_sub(1)); |
| 488 | let older_href = sel.href(&base, sel.state, sel.page + 1); | 488 | let older_href = sel.href(&base, sel.state, sel.page + 1); |
| 489 | - let page_label = g::page_label(lang, sel.page); | 489 | + let page_label = i18n::page_label(lang, sel.page); |
| 490 | 490 | ||
| 491 | let open_href = sel.href(&base, "open", 1); | 491 | let open_href = sel.href(&base, "open", 1); |
| 492 | let closed_href = sel.href(&base, "closed", 1); | 492 | let closed_href = sel.href(&base, "closed", 1); |
| @@ -526,7 +526,7 @@ async fn issues_list_page(cx: &Cx) -> Result<impl View> { | |||
| 526 | let labels_href = repo_href(&owner_name, &repo_name, "labels.css", ""); | 526 | let labels_href = repo_href(&owner_name, &repo_name, "labels.css", ""); |
| 527 | let labels_page_href = repo_href(&owner_name, &repo_name, "labels", ""); | 527 | let labels_page_href = repo_href(&owner_name, &repo_name, "labels", ""); |
| 528 | let milestones_href = repo_href(&owner_name, &repo_name, "milestones", ""); | 528 | let milestones_href = repo_href(&owner_name, &repo_name, "milestones", ""); |
| 529 | - let title = g::issues_title(lang, &format!("{owner_name}/{repo_name}")); | 529 | + let title = g::repo_title(lang, &format!("{owner_name}/{repo_name}"), K::Issues); |
| 530 | let empty_text = if has_filters { | 530 | let empty_text = if has_filters { |
| 531 | g::t(lang, K::NoIssuesMatch) | 531 | g::t(lang, K::NoIssuesMatch) |
| 532 | } else { | 532 | } else { |
| @@ -831,7 +831,11 @@ async fn new_issue_page(cx: &Cx) -> Result<impl View> { | |||
| 831 | } | 831 | } |
| 832 | let state = context::<AppState>(cx); | 832 | let state = context::<AppState>(cx); |
| 833 | let header = ctx.head(state, "issues").await?; | 833 | let header = ctx.head(state, "issues").await?; |
| 834 | - let title = g::new_issue_title(lang, &format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)); | 834 | + let title = g::repo_title( |
| 835 | + lang, | ||
| 836 | + &format!("{}/{}", ctx.repo.owner_name, ctx.repo.name), | ||
| 837 | + K::NewIssue, | ||
| 838 | + ); | ||
| 835 | let csrf = viewer.1.csrf_token.clone(); | 839 | let csrf = viewer.1.csrf_token.clone(); |
| 836 | let found = | 840 | let found = |
| 837 | templates::load_issue_templates(ctx.path.clone(), ctx.repo.default_branch.clone()).await?; | 841 | templates::load_issue_templates(ctx.path.clone(), ctx.repo.default_branch.clone()).await?; |
| @@ -933,8 +937,11 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> { | |||
| 933 | } | 937 | } |
| 934 | Err(message) => { | 938 | Err(message) => { |
| 935 | let header = ctx.head(state, "issues").await?; | 939 | let header = ctx.head(state, "issues").await?; |
| 936 | - let title = | 940 | + let title = g::repo_title( |
| 937 | - g::new_issue_title(lang, &format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)); | 941 | + lang, |
| 942 | + &format!("{}/{}", ctx.repo.owner_name, ctx.repo.name), | ||
| 943 | + K::NewIssue, | ||
| 944 | + ); | ||
| 938 | let csrf = viewer.1.csrf_token.clone(); | 945 | let csrf = viewer.1.csrf_token.clone(); |
| 939 | let draft = DraftIssue { | 946 | let draft = DraftIssue { |
| 940 | title: typed_title, | 947 | title: typed_title, |
crates/forge-web-pages/src/pages/notifications.rsmodified+1 -1
| @@ -998,7 +998,7 @@ pub fn inbox_items(lang: Lang, current: &str, unread_count: u64) -> Vec<RailItem | |||
| 998 | ), | 998 | ), |
| 999 | item( | 999 | item( |
| 1000 | "reviews", | 1000 | "reviews", |
| 1001 | - crate::i18n::authoring::t(lang, crate::i18n::authoring::K::ReviewRequestsTab), | 1001 | + crate::i18n::authoring::t(lang, crate::i18n::authoring::K::ReviewRequests), |
| 1002 | String::new(), | 1002 | String::new(), |
| 1003 | "/review-requests", | 1003 | "/review-requests", |
| 1004 | ), | 1004 | ), |
crates/forge-web-pages/src/pages/repo.rsmodified+2 -2
| @@ -121,7 +121,7 @@ pub async fn repo_head( | |||
| 121 | } | 121 | } |
| 122 | if let Some(source) = mirror { | 122 | if let Some(source) = mirror { |
| 123 | let status = match (source.last_sync, source.last_ok) { | 123 | let status = match (source.last_sync, source.last_ok) { |
| 124 | - (Some(_), Some(true)) => g::mirror_synced(lang).0, | 124 | + (Some(_), Some(true)) => g::mirror_synced(lang), |
| 125 | (Some(_), _) => g::mirror_sync_failed(lang).0, | 125 | (Some(_), _) => g::mirror_sync_failed(lang).0, |
| 126 | (None, _) => g::t(lang, K::NotSyncedYet), | 126 | (None, _) => g::t(lang, K::NotSyncedYet), |
| 127 | }; | 127 | }; |
| @@ -192,7 +192,7 @@ async fn clone_popover( | |||
| 192 | <label for="clone-ssh">"SSH"</label> | 192 | <label for="clone-ssh">"SSH"</label> |
| 193 | <input id="clone-ssh" class="mono" type="text" readonly=(true) value=(ssh.as_str())> | 193 | <input id="clone-ssh" class="mono" type="text" readonly=(true) value=(ssh.as_str())> |
| 194 | if let Some((zip, tar)) = downloads { | 194 | if let Some((zip, tar)) = downloads { |
| 195 | - <nav class="sub" aria-label=(g::t(lang, K::DownloadNav))> | 195 | + <nav class="sub" aria-label=(g::t(lang, K::DownloadLink))> |
| 196 | <a href=(zip)>(g::t(lang, K::DownloadZip))</a> | 196 | <a href=(zip)>(g::t(lang, K::DownloadZip))</a> |
| 197 | <a href=(tar)>(g::t(lang, K::DownloadTarGz))</a> | 197 | <a href=(tar)>(g::t(lang, K::DownloadTarGz))</a> |
| 198 | </nav> | 198 | </nav> |
crates/forge-web-pages/src/pages/repo_mirrors.rsmodified+1 -1
| @@ -61,7 +61,7 @@ const NOTICES: [(&str, K, bool); 7] = [ | |||
| 61 | ("deleted", K::NoticeDeleted, false), | 61 | ("deleted", K::NoticeDeleted, false), |
| 62 | ("pull-created", K::NoticePullCreated, false), | 62 | ("pull-created", K::NoticePullCreated, false), |
| 63 | ("pull-not-empty", K::NoticePullNotEmpty, true), | 63 | ("pull-not-empty", K::NoticePullNotEmpty, true), |
| 64 | - ("confirm", K::NoticeConfirm, true), | 64 | + ("confirm", K::HookNoticeConfirm, true), |
| 65 | ]; | 65 | ]; |
| 66 | 66 | ||
| 67 | /// The add form for a push mirror, or for a pull mirror when `direction` is `pull`. | 67 | /// The add form for a push mirror, or for a pull mirror when `direction` is `pull`. |
crates/forge-web-repo/src/pages/commits.rsmodified+1 -1
| @@ -305,7 +305,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> { | |||
| 305 | let clear_href = format!("/{owner_name}/{repo_name}/commits/{}", url_path(&ref_name)); | 305 | let clear_href = format!("/{owner_name}/{repo_name}/commits/{}", url_path(&ref_name)); |
| 306 | let has_filter = filter.is_some(); | 306 | let has_filter = filter.is_some(); |
| 307 | let filter_text = filter.unwrap_or_default(); | 307 | let filter_text = filter.unwrap_or_default(); |
| 308 | - let page_label = g::page_label(lang, page_no); | 308 | + let page_label = i18n::page_label(lang, page_no); |
| 309 | 309 | ||
| 310 | // Groups by the viewer's day, newest first. Rows keep the order git gave them. | 310 | // Groups by the viewer's day, newest first. Rows keep the order git gave them. |
| 311 | let today = Timestamp::from_second(now) | 311 | let today = Timestamp::from_second(now) |
crates/forge-web-repo/src/pages/discussion_view.rsmodified+1 -1
| @@ -409,7 +409,7 @@ async fn discussion_page( | |||
| 409 | let live_href = item_live_url(&owner, &name, number); | 409 | let live_href = item_live_url(&owner, &name, number); |
| 410 | let header = ctx.head(state, "discussions").await?; | 410 | let header = ctx.head(state, "discussions").await?; |
| 411 | 411 | ||
| 412 | - let comments_label = g::comments_total(lang, discussion.comment_count); | 412 | + let comments_label = g::comments_count(lang, discussion.comment_count); |
| 413 | let mut sub = vec![SubPart::text(category)]; | 413 | let mut sub = vec![SubPart::text(category)]; |
| 414 | if answered { | 414 | if answered { |
| 415 | sub.push(SubPart::text(g::t(lang, K::Answered))); | 415 | sub.push(SubPart::text(g::t(lang, K::Answered))); |
crates/forge-web-repo/src/pages/discussions.rsmodified+1 -1
| @@ -295,7 +295,7 @@ async fn discussions_list_page(cx: &Cx) -> Result<impl View> { | |||
| 295 | }; | 295 | }; |
| 296 | let newer_href = page_param(page.saturating_sub(1)); | 296 | let newer_href = page_param(page.saturating_sub(1)); |
| 297 | let older_href = page_param(page + 1); | 297 | let older_href = page_param(page + 1); |
| 298 | - let page_label = g::page_number(lang, page); | 298 | + let page_label = i18n::page_label(lang, page); |
| 299 | 299 | ||
| 300 | let can_start = ctx.viewer.is_some() && !ctx.repo.archived; | 300 | let can_start = ctx.viewer.is_some() && !ctx.repo.archived; |
| 301 | let live_href = list_live_url(&owner_name, &repo_name); | 301 | let live_href = list_live_url(&owner_name, &repo_name); |
crates/forge-web-repo/src/pages/labels_page.rsmodified+1 -1
| @@ -233,7 +233,7 @@ async fn labels_page(cx: &Cx) -> Result<impl View> { | |||
| 233 | }); | 233 | }); |
| 234 | let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name); | 234 | let live = list_live_url(&ctx.repo.owner_name, &ctx.repo.name); |
| 235 | let css_href = format!("/{}/labels.css", frame.title); | 235 | let css_href = format!("/{}/labels.css", frame.title); |
| 236 | - let page_title = g::labels_title(lang, &frame.title); | 236 | + let page_title = g::repo_title(lang, &frame.title, K::Labels); |
| 237 | Ok(view! { | 237 | Ok(view! { |
| 238 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | 238 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 239 | extra_stylesheet: Some(css_href.as_str()), | 239 | extra_stylesheet: Some(css_href.as_str()), |
crates/forge-web-repo/src/pages/milestones_page.rsmodified+2 -2
| @@ -221,7 +221,7 @@ async fn milestones_page(cx: &Cx) -> Result<impl View> { | |||
| 221 | format!("{}?state={state_name}&page={n}", milestones_href(&title)) | 221 | format!("{}?state={state_name}&page={n}", milestones_href(&title)) |
| 222 | }); | 222 | }); |
| 223 | let empty = rows.is_empty(); | 223 | let empty = rows.is_empty(); |
| 224 | - let page_title = g::milestones_title(lang, &frame.title); | 224 | + let page_title = g::repo_title(lang, &frame.title, K::Milestones); |
| 225 | let csrf = frame.csrf.clone(); | 225 | let csrf = frame.csrf.clone(); |
| 226 | let can_create = frame.can_triage; | 226 | let can_create = frame.can_triage; |
| 227 | let create_action = milestones_href(&frame.title); | 227 | let create_action = milestones_href(&frame.title); |
| @@ -362,7 +362,7 @@ async fn milestone_edit_page(cx: &Cx) -> Result<impl View> { | |||
| 362 | return Err(not_found().into()); | 362 | return Err(not_found().into()); |
| 363 | }; | 363 | }; |
| 364 | let frame = RepoFrame::new(&ctx, context::<AppState>(cx), "issues").await?; | 364 | let frame = RepoFrame::new(&ctx, context::<AppState>(cx), "issues").await?; |
| 365 | - let page_title = g::milestone_edit_title(lang, &frame.title); | 365 | + let page_title = g::repo_title(lang, &frame.title, K::EditMilestone); |
| 366 | let action = format!("{}/{}/edit", milestones_href(&frame.title), milestone.id); | 366 | let action = format!("{}/{}/edit", milestones_href(&frame.title), milestone.id); |
| 367 | let due = milestone.due_on.clone().unwrap_or_default(); | 367 | let due = milestone.due_on.clone().unwrap_or_default(); |
| 368 | let is_open = milestone.state == IssueState::Open; | 368 | let is_open = milestone.state == IssueState::Open; |
crates/forge-web-repo/src/pages/pulls_list.rsmodified+1 -1
| @@ -212,7 +212,7 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> { | |||
| 212 | let has_older = u64::from(sel.page) < last_page; | 212 | let has_older = u64::from(sel.page) < last_page; |
| 213 | let newer_href = sel.href(&base, sel.state, sel.page.saturating_sub(1)); | 213 | let newer_href = sel.href(&base, sel.state, sel.page.saturating_sub(1)); |
| 214 | let older_href = sel.href(&base, sel.state, sel.page + 1); | 214 | let older_href = sel.href(&base, sel.state, sel.page + 1); |
| 215 | - let page_label = g::page_number(lang, sel.page); | 215 | + let page_label = i18n::page_label(lang, sel.page); |
| 216 | 216 | ||
| 217 | let open_href = sel.href(&base, "open", 1); | 217 | let open_href = sel.href(&base, "open", 1); |
| 218 | let closed_href = sel.href(&base, "closed", 1); | 218 | let closed_href = sel.href(&base, "closed", 1); |
crates/forge-web-repo/src/pages/repo_webhooks.rsmodified+1 -1
| @@ -301,7 +301,7 @@ fn header_lines(raw: &str) -> String { | |||
| 301 | fn state_label(lang: Lang, state: DeliveryState) -> (&'static str, &'static str) { | 301 | fn state_label(lang: Lang, state: DeliveryState) -> (&'static str, &'static str) { |
| 302 | match state { | 302 | match state { |
| 303 | DeliveryState::Pending => ("pending", g::t(lang, K::StatePending)), | 303 | DeliveryState::Pending => ("pending", g::t(lang, K::StatePending)), |
| 304 | - DeliveryState::Ok => ("ok", g::t(lang, K::StateOk)), | 304 | + DeliveryState::Ok => ("ok", g::t(lang, K::StatusOk)), |
| 305 | DeliveryState::Failed => ("failed", g::t(lang, K::StateFailed)), | 305 | DeliveryState::Failed => ("failed", g::t(lang, K::StateFailed)), |
| 306 | DeliveryState::GaveUp => ("gave_up", g::t(lang, K::StateGaveUp)), | 306 | DeliveryState::GaveUp => ("gave_up", g::t(lang, K::StateGaveUp)), |
| 307 | } | 307 | } |