forge
Explore
Log in

Don't you dare go Hollow

🔥 remove: every code comment and doc comment in the Rust sources (12k lines), per the no-comments rule; docs/ holds the rationale

Browse files at this commit

7e521edfde549db9434d19632370df17fdf84911Ahmet Kaan GümüşParent: 54c6cdb
All checks have passed
Show checks

300 changed files +21 -7907

Showing the first 300 files; this commit changes more.

crates/forge-ci/build_identity.rsmodified+0 -9
@@ -1,12 +1,3 @@
1-// Build identity for the binary crates. Not a build script of its own: each binary's build.rs pulls
2-// this file in with `include!("../forge-ci/build_identity.rs");` and calls `emit_identity()`. It
3-// emits FORGE_GIT_SHA, FORGE_GIT_DATE and FORGE_GIT_DIRTY for that crate.
4-//
5-// Only release builds read git: the commit, its date and the dirty flag, with a rerun when HEAD
6-// moves. Any other profile emits "unknown" and no per-commit input, so a new commit does not
7-// rebuild debug or test binaries. Release falls back to the FORGE_BUILD_COMMIT and FORGE_BUILD_DATE
8-// environment variables when there is no git (a source tarball, a sandbox without the binary).
9-
10 fn git(args: &[&str]) -> Option<String> {1 fn git(args: &[&str]) -> Option<String> {
11 use std::process::Command;2 use std::process::Command;
12 let out = Command::new("git").args(args).output().ok()?;3 let out = Command::new("git").args(args).output().ok()?;
crates/forge-ci/src/build.rsmodified+0 -16
@@ -1,9 +1,5 @@
1-//! The build identity of this binary: version, git commit, commit date. Shared by the server and
2-//! the runner, which are the same binary, so a runner can be compared to the server it talks to.
3-
4 use std::sync::OnceLock;1 use std::sync::OnceLock;
5 2
6-/// The crate version.
7 pub const VERSION: &str = env!("CARGO_PKG_VERSION");3 pub const VERSION: &str = env!("CARGO_PKG_VERSION");
8 4
9 struct Identity {5 struct Identity {
@@ -14,9 +10,6 @@ struct Identity {
14 10
15 static IDENTITY: OnceLock<Identity> = OnceLock::new();11 static IDENTITY: OnceLock<Identity> = OnceLock::new();
16 12
17-/// Sets the commit, commit date and dirty flag of the running binary. Each binary sets this first
18-/// thing in main, so this crate has no per-commit input and a new commit does not rebuild
19-/// everything that depends on it. A second call is ignored.
20 pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) {13 pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) {
21 let _ = IDENTITY.set(Identity {14 let _ = IDENTITY.set(Identity {
22 commit,15 commit,
@@ -25,22 +18,18 @@ pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) {
25 });18 });
26 }19 }
27 20
28-/// Short git sha of the commit built, or "unknown" before [`set_identity`].
29 pub fn commit() -> &'static str {21 pub fn commit() -> &'static str {
30 IDENTITY.get().map_or("unknown", |i| i.commit)22 IDENTITY.get().map_or("unknown", |i| i.commit)
31 }23 }
32 24
33-/// Commit date (YYYY-MM-DD), or "unknown" before [`set_identity`].
34 pub fn date() -> &'static str {25 pub fn date() -> &'static str {
35 IDENTITY.get().map_or("unknown", |i| i.date)26 IDENTITY.get().map_or("unknown", |i| i.date)
36 }27 }
37 28
38-/// True when the tree had uncommitted changes to tracked files at build time.
39 pub fn dirty() -> bool {29 pub fn dirty() -> bool {
40 IDENTITY.get().is_some_and(|i| i.dirty)30 IDENTITY.get().is_some_and(|i| i.dirty)
41 }31 }
42 32
43-/// `0.1.0 (cf8e648, 2026-10-20)`, with `cf8e648-dirty` for a dirty tree.
44 pub fn display() -> String {33 pub fn display() -> String {
45 format_build(VERSION, commit(), date(), dirty())34 format_build(VERSION, commit(), date(), dirty())
46 }35 }
@@ -50,8 +39,6 @@ pub fn format_build(version: &str, commit: &str, date: &str, dirty: bool) -> Str
50 format!("{version} ({commit}{dirty}, {date})")39 format!("{version} ({commit}{dirty}, {date})")
51 }40 }
52 41
53-/// The commit sha out of a build string made by [`display`], `None` when it is unknown or the
54-/// string is not in that shape.
55 pub fn commit_of(build: &str) -> Option<&str> {42 pub fn commit_of(build: &str) -> Option<&str> {
56 let inner = build.split_once('(')?.1;43 let inner = build.split_once('(')?.1;
57 let commit = inner.split([',', ')']).next()?.trim();44 let commit = inner.split([',', ')']).next()?.trim();
@@ -59,16 +46,13 @@ pub fn commit_of(build: &str) -> Option<&str> {
59 (!commit.is_empty() && commit != "unknown").then_some(commit)46 (!commit.is_empty() && commit != "unknown").then_some(commit)
60 }47 }
61 48
62-/// How a runner's build compares with the server's.
63 #[derive(Debug, Clone, Copy, PartialEq, Eq)]49 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
64 pub enum Freshness {50 pub enum Freshness {
65 UpToDate,51 UpToDate,
66 Outdated,52 Outdated,
67- /// The runner reported nothing usable (an old runner), or this server's own commit is unknown.
68 Unknown,53 Unknown,
69 }54 }
70 55
71-/// Compares by commit, ignoring the dirty marker.
72 pub fn compare(runner: Option<&str>, server: &str) -> Freshness {56 pub fn compare(runner: Option<&str>, server: &str) -> Freshness {
73 match (runner.and_then(commit_of), commit_of(server)) {57 match (runner.and_then(commit_of), commit_of(server)) {
74 (Some(r), Some(s)) if r == s => Freshness::UpToDate,58 (Some(r), Some(s)) if r == s => Freshness::UpToDate,
crates/forge-ci/src/config.rsmodified+3 -135
@@ -1,17 +1,3 @@
1-//! Parser and validator for `.forge/ci.toml`.
2-//!
3-//! ```toml
4-//! [on]
5-//! push = ["main"]
6-//! pull_request = true
7-//!
8-//! [jobs.test]
9-//! image = "docker.io/rust:1"
10-//! run = "cargo test --workspace"
11-//! ```
12-//!
13-//! Globs (`push`, `tags`, `artifacts`) use git-like semantics: `*` does not match `/`, `**` does.
14-
15 use std::collections::{BTreeMap, BTreeSet};1 use std::collections::{BTreeMap, BTreeSet};
16 2
17 use globset::{Glob, GlobBuilder};3 use globset::{Glob, GlobBuilder};
@@ -19,62 +5,40 @@ use serde::{Deserialize, Serialize};
19 5
20 use crate::error::ConfigError;6 use crate::error::ConfigError;
21 7
22-/// Largest accepted `ci.toml`, in bytes.
23 const MAX_CONFIG_BYTES: usize = 64 * 1024;8 const MAX_CONFIG_BYTES: usize = 64 * 1024;
24-/// Largest number of jobs in one workflow.
25 const MAX_JOBS: usize = 20;9 const MAX_JOBS: usize = 20;
26-/// Default job timeout.
27 const DEFAULT_TIMEOUT_MINUTES: u32 = 60;10 const DEFAULT_TIMEOUT_MINUTES: u32 = 60;
28-/// Smallest and largest allowed job timeout.
29 const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360;11 const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360;
30-/// Longest workflow `name`, in characters, after trimming.
31 const MAX_WORKFLOW_NAME_CHARS: usize = 40;12 const MAX_WORKFLOW_NAME_CHARS: usize = 40;
32-/// Largest number of `cache` entries in one job.
33 const MAX_CACHE_ENTRIES: usize = 8;13 const MAX_CACHE_ENTRIES: usize = 8;
34-/// Longest `cache` entry, in characters.
35 const MAX_CACHE_PATH_CHARS: usize = 200;14 const MAX_CACHE_PATH_CHARS: usize = 200;
36-/// Largest number of `[release] assets` entries.
37 const MAX_RELEASE_ASSETS: usize = 32;15 const MAX_RELEASE_ASSETS: usize = 32;
38-/// Longest `[release] title` template, in characters, after trimming.
39 const MAX_RELEASE_TITLE_CHARS: usize = 200;16 const MAX_RELEASE_TITLE_CHARS: usize = 200;
40 17
41-/// Most `[on] schedule` entries.
42 const MAX_SCHEDULES: usize = 8;18 const MAX_SCHEDULES: usize = 8;
43-/// Longest matrix axis value, in characters.
44 const MAX_MATRIX_VALUE_CHARS: usize = 64;19 const MAX_MATRIX_VALUE_CHARS: usize = 64;
45 20
46-/// A parsed and validated workflow.
47 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]21 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48 pub struct CiConfig {22 pub struct CiConfig {
49- /// Optional display name, e.g. `"build"`. The CI badge uses it as its label.
50 #[serde(default)]23 #[serde(default)]
51 pub name: Option<String>,24 pub name: Option<String>,
52- /// The `[on]` table. Optional; defaults to manual runs only.
53 #[serde(rename = "on", default)]25 #[serde(rename = "on", default)]
54 pub on: Triggers,26 pub on: Triggers,
55- /// The `[jobs.<name>]` tables, keyed by job name.
56 #[serde(default)]27 #[serde(default)]
57 pub jobs: BTreeMap<String, JobSpec>,28 pub jobs: BTreeMap<String, JobSpec>,
58- /// The `[release]` table. Optional; when set, a tag run that fully succeeds publishes a release.
59 #[serde(default)]29 #[serde(default)]
60 pub release: Option<ReleaseSpec>,30 pub release: Option<ReleaseSpec>,
61- /// Keys this forge does not know, as dotted paths, e.g. `release` or `jobs.build.foo`. They are
62- /// ignored, not rejected, so a newer `ci.toml` still runs on an older forge. Filled by
63- /// [`parse_config`]; never read from the file.
64 #[serde(skip)]31 #[serde(skip)]
65 pub warnings: Vec<String>,32 pub warnings: Vec<String>,
66 }33 }
67 34
68-/// The `[release]` table. Requires `on.tags`. See docs/ci.md, Releases.
69 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]35 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70 #[serde(default)]36 #[serde(default)]
71 pub struct ReleaseSpec {37 pub struct ReleaseSpec {
72- /// `"<job>:<glob>"` entries. The glob matches the job's flattened artifact names.
73 pub assets: Vec<String>,38 pub assets: Vec<String>,
74 pub prerelease: Prerelease,39 pub prerelease: Prerelease,
75 pub draft: bool,40 pub draft: bool,
76 pub notes: ReleaseNotes,41 pub notes: ReleaseNotes,
77- /// Template with the placeholder `{tag}`, e.g. `"Release {tag}"`.
78 pub title: String,42 pub title: String,
79 }43 }
80 44
@@ -90,10 +54,8 @@ impl Default for ReleaseSpec {
90 }54 }
91 }55 }
92 56
93-/// The `prerelease` key: `"auto"`, `true` or `false`.
94 #[derive(Debug, Clone, Copy, PartialEq, Eq)]57 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
95 pub enum Prerelease {58 pub enum Prerelease {
96- /// A release is a prerelease when its tag contains `-`, e.g. `v1.2.0-rc1`.
97 Auto,59 Auto,
98 Always,60 Always,
99 Never,61 Never,
@@ -128,36 +90,23 @@ impl<'de> Deserialize<'de> for Prerelease {
128 }90 }
129 }91 }
130 92
131-/// The `notes` key.
132 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]93 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
133 #[serde(rename_all = "lowercase")]94 #[serde(rename_all = "lowercase")]
134 pub enum ReleaseNotes {95 pub enum ReleaseNotes {
135- /// One line per commit since the previous release tag.
136 Commits,96 Commits,
137- /// No notes.
138 #[serde(rename = "none")]97 #[serde(rename = "none")]
139 Off,98 Off,
140 }99 }
141 100
142-/// The `[on]` table.
143 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]101 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144 #[serde(default)]102 #[serde(default)]
145 pub struct Triggers {103 pub struct Triggers {
146- /// Branch globs, e.g. `"main"`, `"release/*"`.
147 pub push: Vec<String>,104 pub push: Vec<String>,
148- /// Tag globs, e.g. `"v*"`.
149 pub tags: Vec<String>,105 pub tags: Vec<String>,
150 pub pull_request: bool,106 pub pull_request: bool,
151- /// Defaults to `true`.
152 pub manual: bool,107 pub manual: bool,
153- /// Defaults to `true`. A push to a branch cancels the queued and running runs of
154- /// older commits on that branch.
155 pub cancel_superseded: bool,108 pub cancel_superseded: bool,
156- /// Runs the workflow on each merge queue candidate. Without it, a candidate runs the `push`
157- /// jobs of its target branch (see `docs/merge-queue.md`).
158 pub merge_queue: bool,109 pub merge_queue: bool,
159- /// 5-field cron expressions in UTC, e.g. `"0 3 * * *"`. The server queues a run of the default
160- /// branch head at each match.
161 pub schedule: Vec<String>,110 pub schedule: Vec<String>,
162 }111 }
163 112
@@ -175,47 +124,36 @@ impl Default for Triggers {
175 }124 }
176 }125 }
177 126
178-/// One `[jobs.<name>]` table.
179 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]127 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180 pub struct JobSpec {128 pub struct JobSpec {
181 pub image: String,129 pub image: String,
182 pub run: String,130 pub run: String,
183 #[serde(default)]131 #[serde(default)]
184 pub needs: Vec<String>,132 pub needs: Vec<String>,
185- /// Secret names (`^[A-Z_][A-Z0-9_]{0,63}$`) the job receives.
186 #[serde(default)]133 #[serde(default)]
187 pub secrets: Vec<String>,134 pub secrets: Vec<String>,
188 #[serde(default)]135 #[serde(default)]
189 pub env: BTreeMap<String, String>,136 pub env: BTreeMap<String, String>,
190- /// Relative globs of files to keep after a successful run.
191 #[serde(default)]137 #[serde(default)]
192 pub artifacts: Vec<String>,138 pub artifacts: Vec<String>,
193- /// Runner labels; every label must be present on the runner.
194 #[serde(default)]139 #[serde(default)]
195 pub runs_on: Vec<String>,140 pub runs_on: Vec<String>,
196- /// Workspace-relative directories to keep between runs, e.g. `"target"`. See docs/ci.md, Cache.
197 #[serde(default)]141 #[serde(default)]
198 pub cache: Vec<String>,142 pub cache: Vec<String>,
199 #[serde(default = "default_timeout_minutes")]143 #[serde(default = "default_timeout_minutes")]
200 pub timeout_minutes: u32,144 pub timeout_minutes: u32,
201 #[serde(default = "default_network")]145 #[serde(default = "default_network")]
202 pub network: bool,146 pub network: bool,
203- /// The job's expected peak memory, as `4g` or `512m` in ci.toml. Stored as bytes. The runner
204- /// admits the job only when this much is free, and caps the job's cgroup near it. Absent
205- /// means the runner's default reservation. See docs/ci.md, Memory.
206 #[serde(147 #[serde(
207 default,148 default,
208 deserialize_with = "deserialize_memory",149 deserialize_with = "deserialize_memory",
209 skip_serializing_if = "Option::is_none"150 skip_serializing_if = "Option::is_none"
210 )]151 )]
211 pub memory: Option<u64>,152 pub memory: Option<u64>,
212- /// The `matrix` table. Only present before expansion: [`parse_config`] replaces a matrix job
213- /// with one job per combination, and those have no matrix.
214 #[serde(default, skip_serializing_if = "Option::is_none")]153 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub matrix: Option<MatrixSpec>,154 pub matrix: Option<MatrixSpec>,
216 }155 }
217 156
218-/// A matrix axis value. TOML strings, integers and booleans are all read as text.
219 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]157 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
220 pub struct MatrixValue(pub String);158 pub struct MatrixValue(pub String);
221 159
@@ -242,24 +180,18 @@ impl<'de> Deserialize<'de> for MatrixValue {
242 }180 }
243 }181 }
244 182
245-/// A job's `matrix` table: every key but `exclude` and `include` is an axis with its values.
246 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]183 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
247 pub struct MatrixSpec {184 pub struct MatrixSpec {
248- /// Combinations to drop. An entry matches a combination that agrees on every key it names.
249 #[serde(default)]185 #[serde(default)]
250 pub exclude: Vec<BTreeMap<String, MatrixValue>>,186 pub exclude: Vec<BTreeMap<String, MatrixValue>>,
251- /// Extra combinations. Each names a value for every axis, and may add more keys, which are
252- /// exposed like the axes but are not part of the job name.
253 #[serde(default)]187 #[serde(default)]
254 pub include: Vec<BTreeMap<String, MatrixValue>>,188 pub include: Vec<BTreeMap<String, MatrixValue>>,
255 #[serde(flatten)]189 #[serde(flatten)]
256 pub axes: BTreeMap<String, Vec<MatrixValue>>,190 pub axes: BTreeMap<String, Vec<MatrixValue>>,
257 }191 }
258 192
259-/// Smallest and largest `memory` a job may declare, in bytes.
260 const MEMORY_RANGE_BYTES: std::ops::RangeInclusive<u64> = (64 << 20)..=(1024 << 30);193 const MEMORY_RANGE_BYTES: std::ops::RangeInclusive<u64> = (64 << 20)..=(1024 << 30);
261 194
262-/// Reads `memory` as a size string (`"4g"`) or as a byte count (what the stored spec holds).
263 fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {195 fn deserialize_memory<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
264 #[derive(Deserialize)]196 #[derive(Deserialize)]
265 #[serde(untagged)]197 #[serde(untagged)]
@@ -286,26 +218,16 @@ fn default_network() -> bool {
286 true218 true
287 }219 }
288 220
289-/// Something that can start a workflow run.
290 #[derive(Debug, Clone, Copy, PartialEq, Eq)]221 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
291 pub enum Event<'a> {222 pub enum Event<'a> {
292- Push {223+ Push { branch: &'a str },
293- branch: &'a str,224+ Tag { tag: &'a str },
294- },
295- Tag {
296- tag: &'a str,
297- },
298 PullRequest,225 PullRequest,
299 Manual,226 Manual,
300- /// A `[on] schedule` tick.
301 Schedule,227 Schedule,
302- /// A merge queue candidate for `branch`, the target branch.228+ MergeQueue { branch: &'a str },
303- MergeQueue {
304- branch: &'a str,
305- },
306 }229 }
307 230
308-/// Parses and validates a `ci.toml` document.
309 pub fn parse_config(text: &str) -> Result<CiConfig, ConfigError> {231 pub fn parse_config(text: &str) -> Result<CiConfig, ConfigError> {
310 if text.len() > MAX_CONFIG_BYTES {232 if text.len() > MAX_CONFIG_BYTES {
311 return Err(ConfigError::TooLarge {233 return Err(ConfigError::TooLarge {
@@ -316,7 +238,6 @@ pub fn parse_config(text: &str) -> Result<CiConfig, ConfigError> {
316 let de = toml::Deserializer::parse(text).map_err(|e| ConfigError::Toml(e.to_string()))?;238 let de = toml::Deserializer::parse(text).map_err(|e| ConfigError::Toml(e.to_string()))?;
317 let mut warnings = Vec::new();239 let mut warnings = Vec::new();
318 let mut config: CiConfig = serde_ignored::deserialize(de, |path| {240 let mut config: CiConfig = serde_ignored::deserialize(de, |path| {
319- // serde_ignored marks `Option` wrappers with `?`; they are not part of the key path.
320 let path = path.to_string().replace("?.", "");241 let path = path.to_string().replace("?.", "");
321 warnings.push(format!(242 warnings.push(format!(
322 "unknown key `{path}` ignored: this forge may be older than your ci.toml"243 "unknown key `{path}` ignored: this forge may be older than your ci.toml"
@@ -330,7 +251,6 @@ pub fn parse_config(text: &str) -> Result<CiConfig, ConfigError> {
330 }251 }
331 252
332 impl CiConfig {253 impl CiConfig {
333- /// Whether an event starts this workflow.
334 pub fn triggered_by(&self, ev: &Event) -> bool {254 pub fn triggered_by(&self, ev: &Event) -> bool {
335 match ev {255 match ev {
336 Event::Push { branch } => matches_any(&self.on.push, branch),256 Event::Push { branch } => matches_any(&self.on.push, branch),
@@ -344,14 +264,10 @@ impl CiConfig {
344 }264 }
345 }265 }
346 266
347- /// Whether a run for this event should publish a release when every job succeeds: a
348- /// `[release]` table is set and the event is a tag that matches `on.tags`.
349 pub fn wants_release(&self, ev: &Event) -> bool {267 pub fn wants_release(&self, ev: &Event) -> bool {
350 self.release.is_some() && matches!(ev, Event::Tag { .. }) && self.triggered_by(ev)268 self.release.is_some() && matches!(ev, Event::Tag { .. }) && self.triggered_by(ev)
351 }269 }
352 270
353- /// Job names in dependency order. Ties are broken by name, so the order is stable.
354- /// Jobs in a cycle, or with unknown needs, are left out. [`parse_config`] rejects both.
355 pub fn job_order(&self) -> Vec<&str> {271 pub fn job_order(&self) -> Vec<&str> {
356 let mut remaining: BTreeMap<&str, BTreeSet<&str>> = self272 let mut remaining: BTreeMap<&str, BTreeSet<&str>> = self
357 .jobs273 .jobs
@@ -378,10 +294,6 @@ impl CiConfig {
378 order294 order
379 }295 }
380 296
381- /// Checks every job key, then replaces each matrix job with one job per combination, named
382- /// `base (v1, v2)` with the axis values in axis-name order. Expanded jobs get `MATRIX_<KEY>`
383- /// env entries and `${{ matrix.key }}` (or `${matrix.key}`) filled in `image`, `runs_on` and
384- /// `run`. A `needs` on a matrix job becomes a `needs` on all its combinations.
385 fn expand_matrices(&mut self) -> Result<(), ConfigError> {297 fn expand_matrices(&mut self) -> Result<(), ConfigError> {
386 for name in self.jobs.keys() {298 for name in self.jobs.keys() {
387 if !is_job_name(name) {299 if !is_job_name(name) {
@@ -481,7 +393,6 @@ impl CiConfig {
481 }393 }
482 394
483 impl ReleaseSpec {395 impl ReleaseSpec {
484- /// Whether the release for `tag` is a prerelease.
485 pub fn is_prerelease(&self, tag: &str) -> bool {396 pub fn is_prerelease(&self, tag: &str) -> bool {
486 match self.prerelease {397 match self.prerelease {
487 Prerelease::Auto => tag.contains('-'),398 Prerelease::Auto => tag.contains('-'),
@@ -490,13 +401,10 @@ impl ReleaseSpec {
490 }401 }
491 }402 }
492 403
493- /// The release title for `tag`: the template with `{tag}` replaced.
494 pub fn title_for(&self, tag: &str) -> String {404 pub fn title_for(&self, tag: &str) -> String {
495 self.title.trim().replace("{tag}", tag)405 self.title.trim().replace("{tag}", tag)
496 }406 }
497 407
498- /// Whether an artifact of `job`, under its flattened `artifact_name`, is selected by an
499- /// `assets` entry. Entries that do not name `job` never match.
500 pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool {408 pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool {
501 self.assets.iter().any(|asset| {409 self.assets.iter().any(|asset| {
502 asset_selector(asset).is_some_and(|(selected_job, glob)| {410 asset_selector(asset).is_some_and(|(selected_job, glob)| {
@@ -506,7 +414,6 @@ impl ReleaseSpec {
506 }414 }
507 }415 }
508 416
509-/// Splits an `assets` entry into its job and glob. Validation guarantees the `:`.
510 fn asset_selector(asset: &str) -> Option<(&str, &str)> {417 fn asset_selector(asset: &str) -> Option<(&str, &str)> {
511 asset.split_once(':')418 asset.split_once(':')
512 }419 }
@@ -535,8 +442,6 @@ fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), Config
535 .map_err(|e| invalid(e.to_string()))442 .map_err(|e| invalid(e.to_string()))
536 }443 }
537 444
538-/// A workflow name: non-empty after trimming, at most [`MAX_WORKFLOW_NAME_CHARS`] characters, and
539-/// no control characters.
540 fn validate_workflow_name(name: &str) -> Result<(), ConfigError> {445 fn validate_workflow_name(name: &str) -> Result<(), ConfigError> {
541 let invalid = |reason: &str| ConfigError::InvalidWorkflowName {446 let invalid = |reason: &str| ConfigError::InvalidWorkflowName {
542 name: name.to_string(),447 name: name.to_string(),
@@ -557,7 +462,6 @@ fn validate_workflow_name(name: &str) -> Result<(), ConfigError> {
557 Ok(())462 Ok(())
558 }463 }
559 464
560-/// `^[a-z0-9][a-z0-9_-]{0,39}$`
561 fn is_job_name(name: &str) -> bool {465 fn is_job_name(name: &str) -> bool {
562 let Some((first, rest)) = name.as_bytes().split_first() else {466 let Some((first, rest)) = name.as_bytes().split_first() else {
563 return false;467 return false;
@@ -569,7 +473,6 @@ fn is_job_name(name: &str) -> bool {
569 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-')473 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-')
570 }474 }
571 475
572-/// `^[A-Z_][A-Z0-9_]{0,63}$`, used for secret and env names.
573 fn is_env_name(name: &str) -> bool {476 fn is_env_name(name: &str) -> bool {
574 let Some((first, rest)) = name.as_bytes().split_first() else {477 let Some((first, rest)) = name.as_bytes().split_first() else {
575 return false;478 return false;
@@ -608,8 +511,6 @@ fn validate_artifact(job: &str, pattern: &str) -> Result<(), ConfigError> {
608 .map_err(|e| invalid(&e.to_string()))511 .map_err(|e| invalid(&e.to_string()))
609 }512 }
610 513
611-/// Checks the `cache` entries of one job: at most [`MAX_CACHE_ENTRIES`], each a valid
612-/// [`validate_cache_path`], and no duplicates.
613 fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> {514 fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> {
614 if entries.len() > MAX_CACHE_ENTRIES {515 if entries.len() > MAX_CACHE_ENTRIES {
615 return Err(ConfigError::TooManyCacheEntries {516 return Err(ConfigError::TooManyCacheEntries {
@@ -631,9 +532,6 @@ fn validate_cache(job: &str, entries: &[String]) -> Result<(), ConfigError> {
631 Ok(())532 Ok(())
632 }533 }
633 534
634-/// A cache path is a workspace-relative directory: non-empty, at most [`MAX_CACHE_PATH_CHARS`]
635-/// characters, no leading `/`, no `\`, no empty, `.` or `..` components, no `.git` component, no
636-/// glob characters and no control characters.
637 fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> {535 fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> {
638 let invalid = |reason: &str| ConfigError::InvalidCachePath {536 let invalid = |reason: &str| ConfigError::InvalidCachePath {
639 job: job.to_string(),537 job: job.to_string(),
@@ -673,9 +571,6 @@ fn validate_cache_path(job: &str, path: &str) -> Result<(), ConfigError> {
673 Ok(())571 Ok(())
674 }572 }
675 573
676-/// Checks the `[release]` table against the triggers and jobs: tags must be configured, there
677-/// are at most [`MAX_RELEASE_ASSETS`] assets, each one is valid for [`validate_release_asset`],
678-/// and the title is valid for [`validate_release_title`].
679 fn validate_release(574 fn validate_release(
680 release: &ReleaseSpec,575 release: &ReleaseSpec,
681 on: &Triggers,576 on: &Triggers,
@@ -696,8 +591,6 @@ fn validate_release(
696 validate_release_title(&release.title)591 validate_release_title(&release.title)
697 }592 }
698 593
699-/// An asset is `job:glob`. The job must exist and declare artifacts. The glob is matched against
700-/// flattened artifact names, which never contain `/`, so a glob with `/` is rejected.
701 fn validate_release_asset(594 fn validate_release_asset(
702 asset: &str,595 asset: &str,
703 jobs: &BTreeMap<String, JobSpec>,596 jobs: &BTreeMap<String, JobSpec>,
@@ -728,8 +621,6 @@ fn validate_release_asset(
728 .map_err(|e| invalid(e.to_string()))621 .map_err(|e| invalid(e.to_string()))
729 }622 }
730 623
731-/// A title template: non-blank after trimming, at most [`MAX_RELEASE_TITLE_CHARS`] characters,
732-/// and no control characters.
733 fn validate_release_title(title: &str) -> Result<(), ConfigError> {624 fn validate_release_title(title: &str) -> Result<(), ConfigError> {
734 let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason);625 let invalid = |reason: String| ConfigError::InvalidReleaseTitle(reason);
735 if title.trim().is_empty() {626 if title.trim().is_empty() {
@@ -746,8 +637,6 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> {
746 Ok(())637 Ok(())
747 }638 }
748 639
749-/// Whether `selected` (a job name from the config) names `job`: the job itself, or any
750-/// combination of the matrix job `selected`.
751 fn names_job(selected: &str, job: &str) -> bool {640 fn names_job(selected: &str, job: &str) -> bool {
752 selected == job641 selected == job
753 || job642 || job
@@ -766,10 +655,8 @@ fn is_matrix_key(key: &str) -> bool {
766 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_')655 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_')
767 }656 }
768 657
769-/// One matrix combination: the job name suffix and its variables.
770 type Combination = (String, BTreeMap<String, String>);658 type Combination = (String, BTreeMap<String, String>);
771 659
772-/// The combinations of a matrix as `(name suffix, variables)`, in a stable order.
773 fn combinations(job: &str, matrix: &MatrixSpec) -> Result<Vec<Combination>, ConfigError> {660 fn combinations(job: &str, matrix: &MatrixSpec) -> Result<Vec<Combination>, ConfigError> {
774 let bad = |reason: String| ConfigError::InvalidMatrix {661 let bad = |reason: String| ConfigError::InvalidMatrix {
775 job: job.to_string(),662 job: job.to_string(),
@@ -871,8 +758,6 @@ fn combinations(job: &str, matrix: &MatrixSpec) -> Result<Vec<Combination>, Conf
871 .collect())758 .collect())
872 }759 }
873 760
874-/// A matrix value: non-empty, at most [`MAX_MATRIX_VALUE_CHARS`] characters, no control
875-/// characters, and none of `,`, `(` and `)`, which would make job names ambiguous.
876 fn validate_matrix_value(value: &str) -> Result<(), String> {761 fn validate_matrix_value(value: &str) -> Result<(), String> {
877 if value.is_empty() {762 if value.is_empty() {
878 return Err("values must not be empty".into());763 return Err("values must not be empty".into());
@@ -893,9 +778,6 @@ fn validate_matrix_value(value: &str) -> Result<(), String> {
893 Ok(())778 Ok(())
894 }779 }
895 780
896-/// Replaces `${{ matrix.key }}` and `${matrix.key}` in `text`. A key that is not in `vars` is an
897-/// error, so a typo fails at parse time instead of reaching the shell. Anything else that starts
898-/// with `${` is left alone.
899 fn interpolate(781 fn interpolate(
900 job: &str,782 job: &str,
901 text: &str,783 text: &str,
@@ -1056,7 +938,6 @@ artifacts = ["target/release/forge"]
1056 assert!(lint.env.is_empty());938 assert!(lint.env.is_empty());
1057 }939 }
1058 940
1059- /// Every key with a serde default, in the one place a user would see it.
1060 #[test]941 #[test]
1061 fn defaults_apply_when_keys_are_absent() {942 fn defaults_apply_when_keys_are_absent() {
1062 let cfg = parse_config(&job_toml("")).unwrap();943 let cfg = parse_config(&job_toml("")).unwrap();
@@ -1151,13 +1032,11 @@ artifacts = ["target/release/forge"]
1151 parse_config(&job_toml("")).unwrap().jobs["build"].memory,1032 parse_config(&job_toml("")).unwrap().jobs["build"].memory,
1152 None1033 None
1153 );1034 );
1154- // The stored spec holds bytes and reads back the same.
1155 let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"];1035 let job = &parse_config(&job_toml("memory = \"4g\"")).unwrap().jobs["build"];
1156 let json = serde_json::to_string(job).unwrap();1036 let json = serde_json::to_string(job).unwrap();
1157 assert!(json.contains("\"memory\":4294967296"), "{json}");1037 assert!(json.contains("\"memory\":4294967296"), "{json}");
1158 let back: JobSpec = serde_json::from_str(&json).unwrap();1038 let back: JobSpec = serde_json::from_str(&json).unwrap();
1159 assert_eq!(back.memory, Some(4 << 30));1039 assert_eq!(back.memory, Some(4 << 30));
1160- // A spec stored before the field existed has none.
1161 let old = json.replace(",\"memory\":4294967296", "");1040 let old = json.replace(",\"memory\":4294967296", "");
1162 assert_eq!(serde_json::from_str::<JobSpec>(&old).unwrap().memory, None);1041 assert_eq!(serde_json::from_str::<JobSpec>(&old).unwrap().memory, None);
1163 }1042 }
@@ -1217,7 +1096,6 @@ artifacts = ["target/release/forge"]
1217 err_of(&text),1096 err_of(&text),
1218 ConfigError::TooLarge { max, .. } if max == MAX_CONFIG_BYTES1097 ConfigError::TooLarge { max, .. } if max == MAX_CONFIG_BYTES
1219 ));1098 ));
1220- // Exactly at the limit is accepted.
1221 let mut at_limit = job_toml("");1099 let mut at_limit = job_toml("");
1222 let pad = MAX_CONFIG_BYTES - at_limit.len();1100 let pad = MAX_CONFIG_BYTES - at_limit.len();
1223 at_limit.push_str(&"#".repeat(pad));1101 at_limit.push_str(&"#".repeat(pad));
@@ -1375,7 +1253,6 @@ artifacts = ["target/release/forge"]
1375 "{a,b}".to_string(),1253 "{a,b}".to_string(),
1376 long,1254 long,
1377 ];1255 ];
1378- // A control character, written as a TOML escape.
1379 let text = job_toml(r#"cache = ["a\u0007b"]"#);1256 let text = job_toml(r#"cache = ["a\u0007b"]"#);
1380 assert!(matches!(1257 assert!(matches!(
1381 err_of(&text),1258 err_of(&text),
@@ -1480,7 +1357,6 @@ artifacts = ["target/release/forge"]
1480 [jobs.deploy]\nimage = \"i\"\nrun = \"r\"\nneeds = [\"lint\", \"docs\"]\n";1357 [jobs.deploy]\nimage = \"i\"\nrun = \"r\"\nneeds = [\"lint\", \"docs\"]\n";
1481 let cfg = parse_config(text).unwrap();1358 let cfg = parse_config(text).unwrap();
1482 assert_eq!(cfg.job_order(), vec!["docs", "test", "lint", "deploy"]);1359 assert_eq!(cfg.job_order(), vec!["docs", "test", "lint", "deploy"]);
1483- // Independent jobs come out in name order.
1484 let flat = parse_config(1360 let flat = parse_config(
1485 "[jobs.c]\nimage = \"i\"\nrun = \"r\"\n[jobs.a]\nimage = \"i\"\nrun = \"r\"\n[jobs.b]\nimage = \"i\"\nrun = \"r\"\n",1361 "[jobs.c]\nimage = \"i\"\nrun = \"r\"\n[jobs.a]\nimage = \"i\"\nrun = \"r\"\n[jobs.b]\nimage = \"i\"\nrun = \"r\"\n",
1486 )1362 )
@@ -1535,7 +1411,6 @@ artifacts = ["target/release/forge"]
1535 ));1411 ));
1536 }1412 }
1537 1413
1538- /// A tag-triggered workflow with a `build` job that has artifacts, plus `[release]` body.
1539 fn release_toml(release: &str) -> String {1414 fn release_toml(release: &str) -> String {
1540 format!(1415 format!(
1541 "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n",1416 "[on]\ntags = [\"v*\"]\n{}\n[release]\n{release}\n",
@@ -1699,7 +1574,6 @@ artifacts = ["target/release/forge"]
1699 assert!(release.asset_matches("build", "SHA256SUMS"));1574 assert!(release.asset_matches("build", "SHA256SUMS"));
1700 assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64"));1575 assert!(!release.asset_matches("build", "forge-1.2.0-darwin-arm64"));
1701 assert!(!release.asset_matches("build", "SHA256SUMS.sig"));1576 assert!(!release.asset_matches("build", "SHA256SUMS.sig"));
1702- // The same glob under another job name does not match.
1703 assert!(!release.asset_matches("lint", "SHA256SUMS"));1577 assert!(!release.asset_matches("lint", "SHA256SUMS"));
1704 assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS"));1578 assert!(!ReleaseSpec::default().asset_matches("build", "SHA256SUMS"));
1705 }1579 }
@@ -1784,7 +1658,6 @@ artifacts = ["target/release/forge"]
1784 assert!(!cfg.jobs.contains_key("test (1.85, aarch64)"));1658 assert!(!cfg.jobs.contains_key("test (1.85, aarch64)"));
1785 let extra = &cfg.jobs["test (nightly, x86_64)"];1659 let extra = &cfg.jobs["test (nightly, x86_64)"];
1786 assert_eq!(extra.env["MATRIX_FLAG"], "-Z");1660 assert_eq!(extra.env["MATRIX_FLAG"], "-Z");
1787- // A partial exclude drops every combination that agrees on the named keys.
1788 let m =1661 let m =
1789 r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#;1662 r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#;
1790 let cfg = parse_config(&matrix_toml(m, "")).unwrap();1663 let cfg = parse_config(&matrix_toml(m, "")).unwrap();
@@ -1792,7 +1665,6 @@ artifacts = ["target/release/forge"]
1792 cfg.jobs.keys().collect::<Vec<_>>(),1665 cfg.jobs.keys().collect::<Vec<_>>(),
1793 ["test (stable, x86_64)"]1666 ["test (stable, x86_64)"]
1794 );1667 );
1795- // An include that repeats an existing combination adds nothing.
1796 let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#;1668 let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#;
1797 assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1);1669 assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1);
1798 }1670 }
@@ -1807,7 +1679,6 @@ artifacts = ["target/release/forge"]
1807 assert_eq!(cfg.jobs["ship"].needs.len(), 4);1679 assert_eq!(cfg.jobs["ship"].needs.len(), 4);
1808 let order = cfg.job_order();1680 let order = cfg.job_order();
1809 assert_eq!(order.last(), Some(&"ship"));1681 assert_eq!(order.last(), Some(&"ship"));
1810- // The matrix job's own needs apply to each combination.
1811 let text = format!(1682 let text = format!(
1812 "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}",1683 "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}",
1813 matrix_toml(GRID, "needs = [\"setup\"]")1684 matrix_toml(GRID, "needs = [\"setup\"]")
@@ -1830,7 +1701,6 @@ artifacts = ["target/release/forge"]
1830 }1701 }
1831 );1702 );
1832 assert!(e.to_string().contains("limit is 20"));1703 assert!(e.to_string().contains("limit is 20"));
1833- // Expansion that fits one job but not the workflow hits the job cap.
1834 let mut text = String::new();1704 let mut text = String::new();
1835 for i in 0..MAX_JOBS - 1 {1705 for i in 0..MAX_JOBS - 1 {
1836 text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n"));1706 text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n"));
@@ -1853,11 +1723,9 @@ artifacts = ["target/release/forge"]
1853 "{bad}"1723 "{bad}"
1854 );1724 );
1855 }1725 }
1856- // A typo in an interpolation fails at parse time.
1857 let text =1726 let text =
1858 "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n";1727 "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n";
1859 assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. }));1728 assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. }));
1860- // Plain job keys cannot smuggle a suffix.
1861 let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n";1729 let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n";
1862 assert!(matches!(err_of(text), ConfigError::InvalidJobName(_)));1730 assert!(matches!(err_of(text), ConfigError::InvalidJobName(_)));
1863 }1731 }
crates/forge-ci/src/cron.rsmodified+0 -14
@@ -1,12 +1,6 @@
1-//! Standard 5-field cron expressions in UTC, for `[on] schedule`.
2-//!
3-//! Times are Unix seconds. The functions are pure, so the scheduler's tick logic can be tested
4-//! with a fake clock.
5-
6 use chrono::DateTime;1 use chrono::DateTime;
7 use croner::Cron;2 use croner::Cron;
8 3
9-/// Parses a 5-field cron expression (`minute hour day-of-month month day-of-week`).
10 pub fn parse(expr: &str) -> Result<Cron, String> {4 pub fn parse(expr: &str) -> Result<Cron, String> {
11 let trimmed = expr.trim();5 let trimmed = expr.trim();
12 if trimmed.split_whitespace().count() != 5 {6 if trimmed.split_whitespace().count() != 5 {
@@ -17,15 +11,12 @@ pub fn parse(expr: &str) -> Result<Cron, String> {
17 trimmed.parse::<Cron>().map_err(|e| e.to_string())11 trimmed.parse::<Cron>().map_err(|e| e.to_string())
18 }12 }
19 13
20-/// The first time strictly after `after` that `cron` matches.
21 fn next_one(cron: &Cron, after: i64) -> Option<i64> {14 fn next_one(cron: &Cron, after: i64) -> Option<i64> {
22 let start = DateTime::from_timestamp(after, 0)?.naive_utc();15 let start = DateTime::from_timestamp(after, 0)?.naive_utc();
23 let next = cron.find_next_occurrence(&start, false).ok()?;16 let next = cron.find_next_occurrence(&start, false).ok()?;
24 Some(next.and_utc().timestamp())17 Some(next.and_utc().timestamp())
25 }18 }
26 19
27-/// The first time strictly after `after` that any of `exprs` matches. Expressions that do not
28-/// parse are ignored.
29 pub fn next_after<S: AsRef<str>>(exprs: &[S], after: i64) -> Option<i64> {20 pub fn next_after<S: AsRef<str>>(exprs: &[S], after: i64) -> Option<i64> {
30 exprs21 exprs
31 .iter()22 .iter()
@@ -34,8 +25,6 @@ pub fn next_after<S: AsRef<str>>(exprs: &[S], after: i64) -> Option<i64> {
34 .min()25 .min()
35 }26 }
36 27
37-/// Whether any of `exprs` matched a time `t` with `last < t <= now`. However many ticks fell in
38-/// that window, the answer is one yes: a scheduler that was down catches up once.
39 pub fn fired_between<S: AsRef<str>>(exprs: &[S], last: i64, now: i64) -> bool {28 pub fn fired_between<S: AsRef<str>>(exprs: &[S], last: i64, now: i64) -> bool {
40 next_after(exprs, last).is_some_and(|t| t <= now)29 next_after(exprs, last).is_some_and(|t| t <= now)
41 }30 }
@@ -44,16 +33,13 @@ pub fn fired_between<S: AsRef<str>>(exprs: &[S], last: i64, now: i64) -> bool {
44 mod tests {33 mod tests {
45 use super::*;34 use super::*;
46 35
47- // 2026-10-15 12:00:00 UTC
48 const NOON: i64 = 1_791_979_200;36 const NOON: i64 = 1_791_979_200;
49 37
50 #[test]38 #[test]
51 fn fires_inside_the_window_only() {39 fn fires_inside_the_window_only() {
52 assert!(fired_between(&["30 12 * * *"], NOON, NOON + 1800));40 assert!(fired_between(&["30 12 * * *"], NOON, NOON + 1800));
53 assert!(!fired_between(&["30 12 * * *"], NOON, NOON + 1799));41 assert!(!fired_between(&["30 12 * * *"], NOON, NOON + 1799));
54- // The window is open at `last`: a tick already handled does not fire again.
55 assert!(!fired_between(&["0 12 * * *"], NOON, NOON + 60));42 assert!(!fired_between(&["0 12 * * *"], NOON, NOON + 60));
56- // A week of downtime is still one yes.
57 assert!(fired_between(&["* * * * *"], NOON, NOON + 7 * 86_400));43 assert!(fired_between(&["* * * * *"], NOON, NOON + 7 * 86_400));
58 }44 }
59 }45 }
crates/forge-ci/src/error.rsmodified+0 -3
@@ -1,8 +1,5 @@
1-//! Errors returned by [`crate::config::parse_config`].
2-
3 use thiserror::Error;1 use thiserror::Error;
4 2
5-/// Why a `.forge/ci.toml` file was rejected.
6 #[derive(Debug, Clone, PartialEq, Eq, Error)]3 #[derive(Debug, Clone, PartialEq, Eq, Error)]
7 pub enum ConfigError {4 pub enum ConfigError {
8 #[error("ci config is {size} bytes, the limit is {max} bytes")]5 #[error("ci config is {size} bytes, the limit is {max} bytes")]
crates/forge-ci/src/lib.rsmodified+0 -3
@@ -1,6 +1,3 @@
1-//! CI workflow config (`.forge/ci.toml`), the runner protocol, and log masking. Shared by
2-//! forge-web and forge-runner.
3-
4 pub mod build;1 pub mod build;
5 pub mod config;2 pub mod config;
6 pub mod cron;3 pub mod cron;
crates/forge-ci/src/mask.rsmodified+0 -18
@@ -1,22 +1,14 @@
1-//! Secret masking for job logs. Replaces every secret value, and its standard base64 encoding,
2-//! with `***`. [`MaskStream`] does the same over chunks, so a secret split across two chunks is
3-//! still masked.
4-
5 use std::collections::BTreeSet;1 use std::collections::BTreeSet;
6 use std::fmt;2 use std::fmt;
7 3
8 use base64::Engine as _;4 use base64::Engine as _;
9 use base64::engine::general_purpose::STANDARD;5 use base64::engine::general_purpose::STANDARD;
10 6
11-/// The text that replaces every match.
12 pub const MASK: &str = "***";7 pub const MASK: &str = "***";
13-/// Values shorter than this (in chars) are not masked, since they would hide ordinary output.
14 pub const MIN_SECRET_CHARS: usize = 4;8 pub const MIN_SECRET_CHARS: usize = 4;
15 9
16-/// Masks a fixed set of secret values.
17 #[derive(Clone)]10 #[derive(Clone)]
18 pub struct Masker {11 pub struct Masker {
19- /// Byte patterns (raw values and their base64), longest first, deduplicated.
20 patterns: Vec<Vec<u8>>,12 patterns: Vec<Vec<u8>>,
21 }13 }
22 14
@@ -29,7 +21,6 @@ impl fmt::Debug for Masker {
29 }21 }
30 22
31 impl Masker {23 impl Masker {
32- /// Builds a masker. Values shorter than [`MIN_SECRET_CHARS`] are ignored.
33 pub fn new(secrets: impl IntoIterator<Item = String>) -> Self {24 pub fn new(secrets: impl IntoIterator<Item = String>) -> Self {
34 let mut set: BTreeSet<Vec<u8>> = BTreeSet::new();25 let mut set: BTreeSet<Vec<u8>> = BTreeSet::new();
35 for value in secrets {26 for value in secrets {
@@ -46,12 +37,9 @@ impl Masker {
46 }37 }
47 }38 }
48 39
49-/// Masks a byte stream that arrives in chunks.
50 #[derive(Debug, Clone)]40 #[derive(Debug, Clone)]
51 pub struct MaskStream {41 pub struct MaskStream {
52 masker: Masker,42 masker: Masker,
53- /// Bytes held back because they may be the start of a secret. Never more than the longest
54- /// pattern minus one.
55 held: Vec<u8>,43 held: Vec<u8>,
56 }44 }
57 45
@@ -63,7 +51,6 @@ impl MaskStream {
63 }51 }
64 }52 }
65 53
66- /// Feeds one chunk. Returns the masked bytes that are now safe to emit.
67 pub fn push(&mut self, chunk: &[u8]) -> Vec<u8> {54 pub fn push(&mut self, chunk: &[u8]) -> Vec<u8> {
68 self.held.extend_from_slice(chunk);55 self.held.extend_from_slice(chunk);
69 let (out, rest) = scan(&self.masker.patterns, &self.held, false);56 let (out, rest) = scan(&self.masker.patterns, &self.held, false);
@@ -71,7 +58,6 @@ impl MaskStream {
71 out58 out
72 }59 }
73 60
74- /// Ends the stream and returns whatever is still held back, masked.
75 pub fn finish(&mut self) -> Vec<u8> {61 pub fn finish(&mut self) -> Vec<u8> {
76 let held = std::mem::take(&mut self.held);62 let held = std::mem::take(&mut self.held);
77 let (out, _) = scan(&self.masker.patterns, &held, true);63 let (out, _) = scan(&self.masker.patterns, &held, true);
@@ -79,9 +65,6 @@ impl MaskStream {
79 }65 }
80 }66 }
81 67
82-/// Walks `input` and writes masked bytes. A match is replaced by [`MASK`]. When `last` is false,
83-/// the scan stops at the first position where a pattern could still complete in later input, and
84-/// returns that unprocessed tail. When `last` is true, the whole input is processed.
85 fn scan(patterns: &[Vec<u8>], input: &[u8], last: bool) -> (Vec<u8>, Vec<u8>) {68 fn scan(patterns: &[Vec<u8>], input: &[u8], last: bool) -> (Vec<u8>, Vec<u8>) {
86 let mut out = Vec::with_capacity(input.len());69 let mut out = Vec::with_capacity(input.len());
87 let mut i = 0;70 let mut i = 0;
@@ -141,7 +124,6 @@ mod tests {
141 fn short_values_are_ignored() {124 fn short_values_are_ignored() {
142 let m = masker(&["abc", "", "ab"]);125 let m = masker(&["abc", "", "ab"]);
143 assert_eq!(stream_all(&m, &[b"abc ab"]), "abc ab");126 assert_eq!(stream_all(&m, &[b"abc ab"]), "abc ab");
144- // 4 chars is the minimum that is masked.
145 let m = masker(&["abcd"]);127 let m = masker(&["abcd"]);
146 assert_eq!(stream_all(&m, &[b"xabcdx"]), "x***x");128 assert_eq!(stream_all(&m, &[b"xabcdx"]), "x***x");
147 }129 }
crates/forge-ci/src/proto.rsmodified+0 -98
@@ -1,8 +1,3 @@
1-//! Runner <-> forge JSON protocol. All types use snake_case field names and are serialized as JSON.
2-//!
3-//! Types that carry secrets (`RegisterRequest`, `RegisterResponse`, `JobAssignment`) implement
4-//! `Debug` by hand and print `<redacted>` for their secret fields, so they never end up in logs.
5-
6 use std::collections::BTreeMap;1 use std::collections::BTreeMap;
7 use std::fmt;2 use std::fmt;
8 3
@@ -10,10 +5,8 @@ use serde::{Deserialize, Serialize};
10 5
11 pub const RESTART_EXIT_CODE: u8 = 75;6 pub const RESTART_EXIT_CODE: u8 = 75;
12 7
13-/// `POST /api/v1/ci/runners/register`
14 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]8 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
15 pub struct RegisterRequest {9 pub struct RegisterRequest {
16- /// Single-use registration token, as shown once by the admin page.
17 pub token: String,10 pub token: String,
18 pub name: String,11 pub name: String,
19 pub labels: Vec<String>,12 pub labels: Vec<String>,
@@ -29,11 +22,9 @@ impl fmt::Debug for RegisterRequest {
29 }22 }
30 }23 }
31 24
32-/// Response to [`RegisterRequest`].
33 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]25 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
34 pub struct RegisterResponse {26 pub struct RegisterResponse {
35 pub runner_id: String,27 pub runner_id: String,
36- /// Bearer secret for all later runner calls. Shown to the runner once.
37 pub runner_secret: String,28 pub runner_secret: String,
38 }29 }
39 30
@@ -46,66 +37,42 @@ impl fmt::Debug for RegisterResponse {
46 }37 }
47 }38 }
48 39
49-/// `POST /api/v1/ci/runners/claim`. Long-polls for up to 30s; 204 means nothing was claimed.
50-/// The labels are informational: the server uses the labels stored for the runner.
51 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]40 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
52 pub struct ClaimRequest {41 pub struct ClaimRequest {
53 pub labels: Vec<String>,42 pub labels: Vec<String>,
54- /// The runner's live job concurrency. Absent from an older runner.
55 #[serde(default, skip_serializing_if = "Option::is_none")]43 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub concurrency: Option<u32>,44 pub concurrency: Option<u32>,
57- /// The runner's version, for the admin page.
58 #[serde(default, skip_serializing_if = "Option::is_none")]45 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub version: Option<String>,46 pub version: Option<String>,
60- /// Logical CPUs of the runner's host.
61 #[serde(default, skip_serializing_if = "Option::is_none")]47 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub cpus: Option<u32>,48 pub cpus: Option<u32>,
63- /// Total memory of the runner's host, in bytes.
64 #[serde(default, skip_serializing_if = "Option::is_none")]49 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub memory_bytes: Option<u64>,50 pub memory_bytes: Option<u64>,
66- /// The runner's build identity (`0.1.0 (cf8e648, 2026-10-20)`). Absent from an older runner.
67 #[serde(default, skip_serializing_if = "Option::is_none")]51 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub build: Option<String>,52 pub build: Option<String>,
69- /// Random per process start. The forge sees a restart when it changes.
70 #[serde(default, skip_serializing_if = "Option::is_none")]53 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub boot_id: Option<String>,54 pub boot_id: Option<String>,
72- /// Features this runner has, such as [`CAP_RESTART`]. The crate version is the same for every
73- /// build, so the forge gates features on this list. Absent from an older runner.
74 #[serde(default, skip_serializing_if = "Vec::is_empty")]55 #[serde(default, skip_serializing_if = "Vec::is_empty")]
75 pub capabilities: Vec<String>,56 pub capabilities: Vec<String>,
76- /// Memory the runner can admit right now: its budget minus what running jobs reserved, in
77- /// bytes. The forge hands out only a job whose reservation fits. Absent from an older runner,
78- /// which gets the first job in the queue as before.
79 #[serde(default, skip_serializing_if = "Option::is_none")]57 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub free_memory_bytes: Option<u64>,58 pub free_memory_bytes: Option<u64>,
81- /// The runner's whole memory budget for jobs, in bytes. A job that reserves more than this
82- /// still runs when the runner is idle.
83 #[serde(default, skip_serializing_if = "Option::is_none")]59 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub memory_budget_bytes: Option<u64>,60 pub memory_budget_bytes: Option<u64>,
85- /// What the runner reserves for a job that declares no `memory`, in bytes.
86 #[serde(default, skip_serializing_if = "Option::is_none")]61 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub reserve_memory_bytes: Option<u64>,62 pub reserve_memory_bytes: Option<u64>,
88 }63 }
89 64
90-/// The capability of a runner that obeys [`RESTART_HEADER`].
91 pub const CAP_RESTART: &str = "restart";65 pub const CAP_RESTART: &str = "restart";
92 66
93-/// The capability of a runner that may hand a running job back with [`RequeueRequest`].
94 pub const CAP_REQUEUE: &str = "requeue";67 pub const CAP_REQUEUE: &str = "requeue";
95 68
96-/// `POST /api/v1/ci/jobs/{id}/requeue`: the runner hands a running job back to the queue, for
97-/// example to free memory. The job keeps its place in the queue and starts again from a clean log.
98 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]69 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
99 pub struct RequeueRequest {70 pub struct RequeueRequest {
100 pub reason: String,71 pub reason: String,
101 }72 }
102 73
103-/// The capability of a runner that ships its own log with [`RunnerLogBatch`].
104 pub const CAP_RUNNER_LOG: &str = "runner_log";74 pub const CAP_RUNNER_LOG: &str = "runner_log";
105 75
106-/// `POST /api/v1/ci/runners/log`: lines of the runner's own log (not a job's), so an admin can see
107-/// on the runner's page what it was doing, for example why it claimed nothing. Lines are numbered
108-/// from 0 per process start (`boot_id`); `first_seq` is the number of the first line in `lines`.
109 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]76 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
110 pub struct RunnerLogBatch {77 pub struct RunnerLogBatch {
111 pub boot_id: String,78 pub boot_id: String,
@@ -113,21 +80,15 @@ pub struct RunnerLogBatch {
113 pub lines: Vec<RunnerLogLine>,80 pub lines: Vec<RunnerLogLine>,
114 }81 }
115 82
116-/// One line of a runner's own log.
117 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]83 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
118 pub struct RunnerLogLine {84 pub struct RunnerLogLine {
119- /// Unix time in milliseconds.
120 pub at_ms: i64,85 pub at_ms: i64,
121- /// `error`, `warn`, `info`, `debug` or `trace`.
122 pub level: String,86 pub level: String,
123- /// The formatted message with its fields, without timestamp or level.
124 pub text: String,87 pub text: String,
125 }88 }
126 89
127-/// Longest text kept for one runner log line, in bytes.
128 pub const RUNNER_LOG_MAX_TEXT: usize = 4096;90 pub const RUNNER_LOG_MAX_TEXT: usize = 4096;
129 91
130-/// `text` cut to at most `max` bytes, on a character boundary.
131 pub fn truncate_text(text: &str, max: usize) -> &str {92 pub fn truncate_text(text: &str, max: usize) -> &str {
132 if text.len() <= max {93 if text.len() <= max {
133 return text;94 return text;
@@ -139,59 +100,39 @@ pub fn truncate_text(text: &str, max: usize) -> &str {
139 &text[..end]100 &text[..end]
140 }101 }
141 102
142-/// The answer to a [`RunnerLogBatch`]: the number of the next line the forge wants for this boot
143-/// id. A forge that restarted (or never saw this boot id) answers 0 and the runner resends what it
144-/// still holds; lines it no longer holds are skipped.
145 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]103 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
146 pub struct RunnerLogAck {104 pub struct RunnerLogAck {
147 pub next_seq: u64,105 pub next_seq: u64,
148 }106 }
149 107
150-/// The capability of a runner that sends [`RunnerMetricsBatch`].
151 pub const CAP_RUNNER_METRICS: &str = "runner_metrics";108 pub const CAP_RUNNER_METRICS: &str = "runner_metrics";
152 109
153-/// `POST /api/v1/ci/runners/metrics`: host usage samples, oldest first, for the graphs on the
154-/// runner's admin page. Answered with 204.
155 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]110 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
156 pub struct RunnerMetricsBatch {111 pub struct RunnerMetricsBatch {
157 pub samples: Vec<RunnerSample>,112 pub samples: Vec<RunnerSample>,
158 }113 }
159 114
160-/// One sample of the runner's host. Rates cover the time since the previous sample.
161 #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]115 #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
162 pub struct RunnerSample {116 pub struct RunnerSample {
163- /// Unix time in milliseconds.
164 pub at_ms: i64,117 pub at_ms: i64,
165- /// Busy share of all CPUs, 0 to 100.
166 pub cpu_percent: f32,118 pub cpu_percent: f32,
167- /// Memory in use (total minus available), in bytes.
168 pub mem_used_bytes: u64,119 pub mem_used_bytes: u64,
169 pub mem_total_bytes: u64,120 pub mem_total_bytes: u64,
170- /// Received and sent bytes per second over every interface but loopback.
171 pub net_rx_bytes_per_s: u64,121 pub net_rx_bytes_per_s: u64,
172 pub net_tx_bytes_per_s: u64,122 pub net_tx_bytes_per_s: u64,
173- /// Used and total bytes of the filesystem holding the runner's work dir. Zero from older runners.
174 #[serde(default)]123 #[serde(default)]
175 pub disk_used_bytes: u64,124 pub disk_used_bytes: u64,
176 #[serde(default)]125 #[serde(default)]
177 pub disk_total_bytes: u64,126 pub disk_total_bytes: u64,
178- /// Jobs running on the runner.
179 pub running_jobs: u32,127 pub running_jobs: u32,
180 }128 }
181 129
182-/// Response header on a claim: an admin asked this runner to restart. The value is `drain` (finish
183-/// the running jobs first) or `now` (cancel them). Absent means no request. The runner stops
184-/// claiming, restarts the way a self-update does (exit 75), and the forge clears
185-/// the request when it sees a new boot id.
186 pub const RESTART_HEADER: &str = "Forge-Runner-Restart";130 pub const RESTART_HEADER: &str = "Forge-Runner-Restart";
187 131
188-/// How a runner restarts when an admin asks.
189 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]132 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
190 #[serde(rename_all = "lowercase")]133 #[serde(rename_all = "lowercase")]
191 pub enum RestartMode {134 pub enum RestartMode {
192- /// Stop claiming, let the running jobs finish, then restart.
193 Drain,135 Drain,
194- /// Cancel the running jobs, then restart.
195 Now,136 Now,
196 }137 }
197 138
@@ -203,7 +144,6 @@ impl RestartMode {
203 }144 }
204 }145 }
205 146
206- /// Parses a header value. Anything else counts as no request.
207 pub fn parse(text: &str) -> Option<Self> {147 pub fn parse(text: &str) -> Option<Self> {
208 match text.trim() {148 match text.trim() {
209 "drain" => Some(Self::Drain),149 "drain" => Some(Self::Drain),
@@ -213,34 +153,22 @@ impl RestartMode {
213 }153 }
214 }154 }
215 155
216-/// Request header on a heartbeat: the runner's build identity, same value as `ClaimRequest::build`.
217 pub const BUILD_HEADER: &str = "Forge-Runner-Build";156 pub const BUILD_HEADER: &str = "Forge-Runner-Build";
218 157
219-/// Response header on a claim: the concurrency an admin set for this runner in the web UI. Absent
220-/// when there is no override, which means the runner uses the value from its own `runner.toml`.
221 pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency";158 pub const CONCURRENCY_HEADER: &str = "Forge-Runner-Concurrency";
222 159
223-/// Response header on a claim: the memory budget an admin set for this runner in the web UI
224-/// (`6g`). Absent means no override. Live, like [`CONCURRENCY_HEADER`].
225 pub const MEMORY_BUDGET_HEADER: &str = "Forge-Runner-Memory-Budget";160 pub const MEMORY_BUDGET_HEADER: &str = "Forge-Runner-Memory-Budget";
226 161
227-/// Response header on a claim: the default memory reservation an admin set (`1g`). Absent means no
228-/// override.
229 pub const RESERVE_MEMORY_HEADER: &str = "Forge-Runner-Reserve-Memory";162 pub const RESERVE_MEMORY_HEADER: &str = "Forge-Runner-Reserve-Memory";
230 163
231-/// The smallest and largest job concurrency a runner accepts.
232 pub const MIN_CONCURRENCY: u32 = 1;164 pub const MIN_CONCURRENCY: u32 = 1;
233 pub const MAX_CONCURRENCY: u32 = 64;165 pub const MAX_CONCURRENCY: u32 = 64;
234 166
235-/// Returned with 200 by the claim endpoint.
236 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]167 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
237 pub struct JobAssignment {168 pub struct JobAssignment {
238 pub job_id: String,169 pub job_id: String,
239- /// Bearer token for `/api/v1/ci/jobs/{id}/...` and for read-only git access.
240 pub job_token: String,170 pub job_token: String,
241- /// `owner/name`.
242 pub repo: String,171 pub repo: String,
243- /// HTTPS clone URL of the repo.
244 pub clone_url: String,172 pub clone_url: String,
245 pub commit: String,173 pub commit: String,
246 pub git_ref: String,174 pub git_ref: String,
@@ -248,23 +176,16 @@ pub struct JobAssignment {
248 pub image: String,176 pub image: String,
249 pub run: String,177 pub run: String,
250 pub env: BTreeMap<String, String>,178 pub env: BTreeMap<String, String>,
251- /// Secret values, by name. Never print these.
252 pub secrets: BTreeMap<String, String>,179 pub secrets: BTreeMap<String, String>,
253 pub artifacts: Vec<String>,180 pub artifacts: Vec<String>,
254 pub timeout_minutes: u32,181 pub timeout_minutes: u32,
255 pub network: bool,182 pub network: bool,
256- /// Workspace-relative directories to cache, already validated. Empty when the job has no cache.
257 #[serde(default, skip_serializing_if = "Vec::is_empty")]183 #[serde(default, skip_serializing_if = "Vec::is_empty")]
258 pub cache: Vec<String>,184 pub cache: Vec<String>,
259- /// The cache scope this job may write, e.g. `ref:refs/heads/main` or `pr:12`. Empty means the
260- /// runner neither restores nor saves a cache for this job. The runner namespaces it by repo and job.
261 #[serde(default, skip_serializing_if = "String::is_empty")]185 #[serde(default, skip_serializing_if = "String::is_empty")]
262 pub cache_key: String,186 pub cache_key: String,
263- /// Read-only fallback scopes, tried in order when `cache_key` has no entry. Never written.
264 #[serde(default, skip_serializing_if = "Vec::is_empty")]187 #[serde(default, skip_serializing_if = "Vec::is_empty")]
265 pub cache_restore_keys: Vec<String>,188 pub cache_restore_keys: Vec<String>,
266- /// The job's declared peak memory in bytes (`memory` in ci.toml). Absent when the job did not
267- /// declare one, and from an older forge: the runner then reserves its default.
268 #[serde(default, skip_serializing_if = "Option::is_none")]189 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub memory_bytes: Option<u64>,190 pub memory_bytes: Option<u64>,
270 }191 }
@@ -294,53 +215,37 @@ impl fmt::Debug for JobAssignment {
294 }215 }
295 }216 }
296 217
297-/// `PUT /api/v1/ci/runners/config`: the runner's effective `runner.toml` as flat JSON by dotted key
298-/// (`limits.memory`). Secrets are redacted by the runner before they get here.
299 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]218 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
300 pub struct RunnerConfigReport {219 pub struct RunnerConfigReport {
301 pub config: BTreeMap<String, serde_json::Value>,220 pub config: BTreeMap<String, serde_json::Value>,
302 }221 }
303 222
304-/// Response to `GET` and `PUT /api/v1/ci/runners/config`: the values an admin set in the web UI,
305-/// by the same dotted keys. A key that is absent has no override. The runner applies the
306-/// restart-time ones when it starts; `concurrency` and `labels` are live and travel elsewhere.
307 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]223 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
308 pub struct RunnerConfigOverrides {224 pub struct RunnerConfigOverrides {
309 #[serde(default)]225 #[serde(default)]
310 pub overrides: BTreeMap<String, serde_json::Value>,226 pub overrides: BTreeMap<String, serde_json::Value>,
311 }227 }
312 228
313-/// Response to `POST /api/v1/ci/jobs/{id}/heartbeat`.
314 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]229 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
315 pub struct HeartbeatResponse {230 pub struct HeartbeatResponse {
316 pub cancel: bool,231 pub cancel: bool,
317- /// The concurrency an admin set in the web UI. Absent means no override (use `runner.toml`).
318- /// A runner at its limit does not claim, so it learns about a change from its heartbeats.
319 #[serde(default, skip_serializing_if = "Option::is_none")]232 #[serde(default, skip_serializing_if = "Option::is_none")]
320 pub concurrency: Option<u32>,233 pub concurrency: Option<u32>,
321- /// A restart an admin asked for. Absent from a forge that does not know the feature.
322 #[serde(default, skip_serializing_if = "Option::is_none")]234 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub restart: Option<RestartMode>,235 pub restart: Option<RestartMode>,
324 }236 }
325 237
326-/// `POST /api/v1/ci/jobs/{id}/finish`.
327 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]238 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
328 pub struct FinishRequest {239 pub struct FinishRequest {
329 pub outcome: Outcome,240 pub outcome: Outcome,
330 pub exit_code: Option<i32>,241 pub exit_code: Option<i32>,
331 pub message: Option<String>,242 pub message: Option<String>,
332- /// True when the OOM killer killed a process in the job's cgroup, read from its
333- /// `memory.events`. This is what shows an OOM kill that the job survived: cargo reports a
334- /// killed rustc in the log and exits 101. Absent from an older runner, from a runner that
335- /// cannot read the cgroup, and when nothing was killed.
336 #[serde(default, skip_serializing_if = "Option::is_none")]243 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub oom_killed: Option<bool>,244 pub oom_killed: Option<bool>,
338- /// How many processes the OOM killer took in the job's cgroup (`oom_kill`).
339 #[serde(default, skip_serializing_if = "Option::is_none")]245 #[serde(default, skip_serializing_if = "Option::is_none")]
340 pub oom_kills: Option<u32>,246 pub oom_kills: Option<u32>,
341 }247 }
342 248
343-/// Final result of a job, reported by the runner.
344 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]249 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
345 #[serde(rename_all = "snake_case")]250 #[serde(rename_all = "snake_case")]
346 pub enum Outcome {251 pub enum Outcome {
@@ -364,7 +269,6 @@ mod tests {
364 fn old_and_new_claim_and_heartbeat_bodies_parse() {269 fn old_and_new_claim_and_heartbeat_bodies_parse() {
365 let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap();270 let old: ClaimRequest = serde_json::from_str(r#"{"labels":["linux"]}"#).unwrap();
366 assert_eq!(old.concurrency, None);271 assert_eq!(old.concurrency, None);
367- // An old runner sends no memory fields, so the forge applies no memory filter.
368 assert_eq!(old.free_memory_bytes, None);272 assert_eq!(old.free_memory_bytes, None);
369 assert_eq!(old.reserve_memory_bytes, None);273 assert_eq!(old.reserve_memory_bytes, None);
370 let json = serde_json::to_string(&old).unwrap();274 let json = serde_json::to_string(&old).unwrap();
@@ -405,7 +309,6 @@ mod tests {
405 oom_kills: None,309 oom_kills: None,
406 };310 };
407 let json = serde_json::to_string(&req).unwrap();311 let json = serde_json::to_string(&req).unwrap();
408- // An old runner's body, and a new runner that saw no OOM kill, look the same.
409 assert_eq!(312 assert_eq!(
410 json,313 json,
411 r#"{"outcome":"failure","exit_code":2,"message":null}"#314 r#"{"outcome":"failure","exit_code":2,"message":null}"#
@@ -449,7 +352,6 @@ mod tests {
449 };352 };
450 let json = serde_json::to_string(&job).unwrap();353 let json = serde_json::to_string(&job).unwrap();
451 assert!(!json.contains("cache"), "{json}");354 assert!(!json.contains("cache"), "{json}");
452- // An older server's reply, without the cache fields, still parses.
453 let back: JobAssignment = serde_json::from_str(&json).unwrap();355 let back: JobAssignment = serde_json::from_str(&json).unwrap();
454 assert_eq!(back, job);356 assert_eq!(back, job);
455 }357 }
crates/forge-ci/src/size.rsmodified+0 -6
@@ -1,7 +1,3 @@
1-//! Byte sizes such as `4g` or `512m`, for `memory` in ci.toml and the runner's memory settings.
2-
3-/// Parses `4g`, `512m`, `1.5g`, `64k`, `4gb`, `4GiB`, `1t` or a plain byte count. Units are
4-/// powers of 1024. `None` for anything else, for zero and for a size that overflows.
5 pub fn parse_size(text: &str) -> Option<u64> {1 pub fn parse_size(text: &str) -> Option<u64> {
6 let lower = text.trim().to_ascii_lowercase();2 let lower = text.trim().to_ascii_lowercase();
7 let split = lower3 let split = lower
@@ -34,8 +30,6 @@ pub fn parse_size(text: &str) -> Option<u64> {
34 (bytes > 0).then_some(bytes)30 (bytes > 0).then_some(bytes)
35 }31 }
36 32
37-/// Formats a byte count the way an admin would type it: `4g`, `512m`, or plain bytes when it is
38-/// not a whole number of MiB.
39 pub fn format_size(bytes: u64) -> String {33 pub fn format_size(bytes: u64) -> String {
40 const GIB: u64 = 1 << 30;34 const GIB: u64 = 1 << 30;
41 const MIB: u64 = 1 << 20;35 const MIB: u64 = 1 << 20;
crates/forge-ci/src/steps.rsmodified+0 -13
@@ -1,30 +1,18 @@
1-//! Job steps from the log: `::group::Name` opens a step and `::endgroup::` closes it, the way the
2-//! browser's log viewer reads them. Only top-level groups are steps; nested groups add no marks.
3-
4-/// The most steps kept per job. Later top-level groups are not stored.
5 pub const MAX_STEPS: usize = 32;1 pub const MAX_STEPS: usize = 32;
6-/// The longest step name, in characters. Longer names are cut.
7 pub const MAX_STEP_NAME_CHARS: usize = 80;2 pub const MAX_STEP_NAME_CHARS: usize = 80;
8 3
9-/// A change of step state found in a log line.
10 #[derive(Debug, Clone, PartialEq, Eq)]4 #[derive(Debug, Clone, PartialEq, Eq)]
11 pub enum StepMark {5 pub enum StepMark {
12- /// A top-level group opened. `offset` is the byte position of its line in the log.
13 Start { name: String, offset: u64 },6 Start { name: String, offset: u64 },
14- /// The open top-level group closed.
15 End,7 End,
16 }8 }
17 9
18-/// The marks found in the complete lines of a chunk, and how many bytes of it they used.
19 #[derive(Debug, Clone, PartialEq, Eq)]10 #[derive(Debug, Clone, PartialEq, Eq)]
20 pub struct Scan {11 pub struct Scan {
21 pub marks: Vec<StepMark>,12 pub marks: Vec<StepMark>,
22- /// Bytes through the last newline. A partial last line is left for the next scan.
23 pub consumed: usize,13 pub consumed: usize,
24 }14 }
25 15
26-/// Reads the complete lines of `bytes`, which start at log byte `base_offset`. `depth` is the
27-/// number of open groups and carries over between scans.
28 pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan {16 pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan {
29 let mut marks = Vec::new();17 let mut marks = Vec::new();
30 let mut start = 0;18 let mut start = 0;
@@ -59,7 +47,6 @@ pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan {
59 }47 }
60 }48 }
61 49
62-/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line.
63 pub fn strip_ansi(line: &str) -> String {50 pub fn strip_ansi(line: &str) -> String {
64 let mut out = String::with_capacity(line.len());51 let mut out = String::with_capacity(line.len());
65 let mut chars = line.chars().peekable();52 let mut chars = line.chars().peekable();
crates/forge-core/src/advisories.rsmodified+0 -36
@@ -1,12 +1,3 @@
1-//! Security advisories: the OSV records read from a dump, the version ranges they name, and the
2-//! lockfile parsers that turn a repo's `Cargo.lock`, `package-lock.json` and `go.sum` into
3-//! dependencies. Storage is in `store/advisories.rs`; the download and the scan are in forge-web.
4-//!
5-//! Only the OSV fields the forge needs are read: `id`, `summary`, `aliases`, `severity`,
6-//! `affected[].package`, `affected[].ranges` (SEMVER and ECOSYSTEM events) and
7-//! `affected[].versions`. Git ranges are skipped. Versions are compared as semver: a leading `v`
8-//! is dropped first, so Go versions and Go pseudo-versions compare as semver too.
9-
10 use std::collections::{BTreeMap, BTreeSet};1 use std::collections::{BTreeMap, BTreeSet};
11 use std::io::{Read, Seek};2 use std::io::{Read, Seek};
12 3
@@ -15,13 +6,10 @@ use serde_json::Value;
15 6
16 use crate::error::{Error, Result};7 use crate::error::{Error, Result};
17 8
18-/// The OSV ecosystem names the forge knows how to scan. `[advisories] ecosystems` picks a subset.
19 pub const KNOWN_ECOSYSTEMS: [&str; 3] = ["crates.io", "npm", "Go"];9 pub const KNOWN_ECOSYSTEMS: [&str; 3] = ["crates.io", "npm", "Go"];
20 10
21-/// Largest single OSV record read from a dump. Real records are a few KiB.
22 const MAX_RECORD_BYTES: u64 = 4 * 1024 * 1024;11 const MAX_RECORD_BYTES: u64 = 4 * 1024 * 1024;
23 12
24-/// One event of a range, in the order it appears in the record.
25 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]13 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26 #[serde(rename_all = "snake_case")]14 #[serde(rename_all = "snake_case")]
27 pub enum Event {15 pub enum Event {
@@ -31,13 +19,11 @@ pub enum Event {
31 Limit(String),19 Limit(String),
32 }20 }
33 21
34-/// One SEMVER or ECOSYSTEM range of an affected package.
35 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]22 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36 pub struct Range {23 pub struct Range {
37 pub events: Vec<Event>,24 pub events: Vec<Event>,
38 }25 }
39 26
40-/// An advisory as it applies to one package in one ecosystem.
41 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]27 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42 pub struct Advisory {28 pub struct Advisory {
43 pub id: String,29 pub id: String,
@@ -52,7 +38,6 @@ pub struct Advisory {
52 pub versions: Vec<String>,38 pub versions: Vec<String>,
53 }39 }
54 40
55-/// A package version read from a lockfile.
56 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]41 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
57 pub struct Dependency {42 pub struct Dependency {
58 pub ecosystem: String,43 pub ecosystem: String,
@@ -118,8 +103,6 @@ struct RawEvent {
118 limit: Option<String>,103 limit: Option<String>,
119 }104 }
120 105
121-/// Parses one OSV record into one [`Advisory`] per affected package of `ecosystem`. Several
122-/// `affected` entries for the same package are merged into one advisory.
123 pub fn parse_record(json: &[u8], ecosystem: &str) -> Result<Vec<Advisory>> {106 pub fn parse_record(json: &[u8], ecosystem: &str) -> Result<Vec<Advisory>> {
124 let record: Record = serde_json::from_slice(json)107 let record: Record = serde_json::from_slice(json)
125 .map_err(|e| Error::Invalid(format!("advisory record is not valid OSV: {e}")))?;108 .map_err(|e| Error::Invalid(format!("advisory record is not valid OSV: {e}")))?;
@@ -182,13 +165,8 @@ pub fn parse_record(json: &[u8], ecosystem: &str) -> Result<Vec<Advisory>> {
182 Ok(merged.into_values().collect())165 Ok(merged.into_values().collect())
183 }166 }
184 167
185-/// Advisories handed to the sink of [`read_dump`] at a time.
186 const IMPORT_BATCH: usize = 500;168 const IMPORT_BATCH: usize = 500;
187 169
188-/// Reads every `.json` record of an OSV zip dump for `ecosystem`, handing the advisories to `sink`
189-/// in batches of about [`IMPORT_BATCH`], so the whole dump is never held in memory. A record that
190-/// does not parse, or is too large, is skipped and counted in the returned value. An error from
191-/// the sink or from a broken zip stops the read and is returned.
192 pub fn read_dump<R, F>(reader: R, ecosystem: &str, mut sink: F) -> Result<usize>170 pub fn read_dump<R, F>(reader: R, ecosystem: &str, mut sink: F) -> Result<usize>
193 where171 where
194 R: Read + Seek,172 R: Read + Seek,
@@ -227,13 +205,10 @@ where
227 Ok(skipped)205 Ok(skipped)
228 }206 }
229 207
230-/// Parses a version as semver, after dropping a leading `v` (Go style).
231 pub fn parse_version(raw: &str) -> Option<semver::Version> {208 pub fn parse_version(raw: &str) -> Option<semver::Version> {
232 semver::Version::parse(raw.trim().trim_start_matches('v')).ok()209 semver::Version::parse(raw.trim().trim_start_matches('v')).ok()
233 }210 }
234 211
235-/// Whether `advisory` covers `version` of its package. A version listed in `versions` matches by
236-/// text. Otherwise the version must fall inside one of the ranges.
237 pub fn affects(advisory: &Advisory, version: &str) -> bool {212 pub fn affects(advisory: &Advisory, version: &str) -> bool {
238 let wanted = version.trim().trim_start_matches('v');213 let wanted = version.trim().trim_start_matches('v');
239 if advisory214 if advisory
@@ -252,9 +227,6 @@ pub fn affects(advisory: &Advisory, version: &str) -> bool {
252 .any(|range| range_affects(range, &parsed))227 .any(|range| range_affects(range, &parsed))
253 }228 }
254 229
255-/// Walks the events of one range. An interval runs from an `introduced` event to the next
256-/// `fixed` (exclusive) or `last_affected` (inclusive). `introduced` of `0` starts at the beginning.
257-/// An interval still open at the end runs forever.
258 fn range_affects(range: &Range, version: &semver::Version) -> bool {230 fn range_affects(range: &Range, version: &semver::Version) -> bool {
259 let mut open: Option<Option<semver::Version>> = None;231 let mut open: Option<Option<semver::Version>> = None;
260 for event in &range.events {232 for event in &range.events {
@@ -288,8 +260,6 @@ fn starts_before(start: &Option<semver::Version>, version: &semver::Version) ->
288 start.as_ref().is_none_or(|s| version >= s)260 start.as_ref().is_none_or(|s| version >= s)
289 }261 }
290 262
291-/// Reads `Cargo.lock`. Only registry packages count: path and git packages have no `source`
292-/// from crates.io and are skipped.
293 pub fn parse_cargo_lock(text: &str, manifest_path: &str) -> Result<Vec<Dependency>> {263 pub fn parse_cargo_lock(text: &str, manifest_path: &str) -> Result<Vec<Dependency>> {
294 #[derive(Deserialize)]264 #[derive(Deserialize)]
295 struct Lock {265 struct Lock {
@@ -317,8 +287,6 @@ pub fn parse_cargo_lock(text: &str, manifest_path: &str) -> Result<Vec<Dependenc
317 .collect())287 .collect())
318 }288 }
319 289
320-/// Reads `package-lock.json` in the v2 and v3 `packages` layout. Entries without a version, the
321-/// root entry and linked workspace packages are skipped.
322 pub fn parse_package_lock(text: &str, manifest_path: &str) -> Result<Vec<Dependency>> {290 pub fn parse_package_lock(text: &str, manifest_path: &str) -> Result<Vec<Dependency>> {
323 let doc: Value = serde_json::from_str(text)291 let doc: Value = serde_json::from_str(text)
324 .map_err(|e| Error::Invalid(format!("package-lock.json is not valid JSON: {e}")))?;292 .map_err(|e| Error::Invalid(format!("package-lock.json is not valid JSON: {e}")))?;
@@ -333,7 +301,6 @@ pub fn parse_package_lock(text: &str, manifest_path: &str) -> Result<Vec<Depende
333 let Some(version) = entry.get("version").and_then(Value::as_str) else {301 let Some(version) = entry.get("version").and_then(Value::as_str) else {
334 continue;302 continue;
335 };303 };
336- // `node_modules/a/node_modules/@s/b` names `@s/b`: the part after the last `node_modules/`.
337 let name = match key.rsplit_once("node_modules/") {304 let name = match key.rsplit_once("node_modules/") {
338 Some((_, name)) => name,305 Some((_, name)) => name,
339 None => continue,306 None => continue,
@@ -348,8 +315,6 @@ pub fn parse_package_lock(text: &str, manifest_path: &str) -> Result<Vec<Depende
348 Ok(out)315 Ok(out)
349 }316 }
350 317
351-/// Reads `go.sum`. Each module version is listed once, with or without its `/go.mod` hash line;
352-/// the `/go.mod` lines alone are not dependencies, so they are dropped.
353 pub fn parse_go_sum(text: &str, manifest_path: &str) -> Vec<Dependency> {318 pub fn parse_go_sum(text: &str, manifest_path: &str) -> Vec<Dependency> {
354 let mut seen = BTreeSet::new();319 let mut seen = BTreeSet::new();
355 for line in text.lines() {320 for line in text.lines() {
@@ -405,7 +370,6 @@ mod tests {
405 370
406 #[test]371 #[test]
407 fn range_events_match_by_table() {372 fn range_events_match_by_table() {
408- // (case name, range events, (version, expected affected) checks)
409 type Case<'a> = (&'a str, Vec<Event>, Vec<(&'a str, bool)>);373 type Case<'a> = (&'a str, Vec<Event>, Vec<(&'a str, bool)>);
410 let cases: Vec<Case> = vec![374 let cases: Vec<Case> = vec![
411 (375 (
crates/forge-core/src/alerts.rsmodified+0 -22
@@ -1,25 +1,13 @@
1-//! Admin alerts: the kinds of trouble the forge tells its admins about, and the pure rules that
2-//! decide when to. Delivery and state live in `store::admin_alerts` and forge-web's `alerts`.
3-
4-/// What an alert is about. Each kind has its own on/off setting.
5 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]1 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6 pub enum AlertKind {2 pub enum AlertKind {
7- /// A CI runner stopped checking in.
8 RunnerOffline,3 RunnerOffline,
9- /// A backup, its verification or an fsck failed, or no backup succeeded in time.
10 Backup,4 Backup,
11- /// The data directory is nearly full.
12 Disk,5 Disk,
13- /// A CI job was killed by SIGKILL or the OOM killer.
14 CiKilled,6 CiKilled,
15- /// A self-update deployed or failed, and the server restarted.
16 SelfUpdate,7 SelfUpdate,
17- /// The standby is failing or lagging.
18 Replication,8 Replication,
19 }9 }
20 10
21-/// Whether a job's result looks like the process was killed: SIGKILL (`signal: 9`, `SIGKILL`,
22-/// `Killed`), the shell's `128 + 9` exit code, or an out-of-memory message.
23 pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool {11 pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool {
24 if matches!(exit_code, Some(137) | Some(-9)) {12 if matches!(exit_code, Some(137) | Some(-9)) {
25 return true;13 return true;
@@ -39,8 +27,6 @@ pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool
39 {27 {
40 return true;28 return true;
41 }29 }
42- // "signal: 9", "signal 9", "signal=9", "killed by signal 9". A longer number such as 90 is
43- // not a match.
44 let mut rest = text.as_str();30 let mut rest = text.as_str();
45 while let Some(at) = rest.find("signal") {31 while let Some(at) = rest.find("signal") {
46 rest = &rest[at + "signal".len()..];32 rest = &rest[at + "signal".len()..];
@@ -56,23 +42,18 @@ pub fn is_kill_signature(exit_code: Option<i64>, message: Option<&str>) -> bool
56 text.trim() == "killed"42 text.trim() == "killed"
57 }43 }
58 44
59-/// Free space as a percentage of the total, rounded down. `None` for an empty filesystem.
60 pub fn free_percent(total: u64, available: u64) -> Option<u64> {45 pub fn free_percent(total: u64, available: u64) -> Option<u64> {
61 (u128::from(available) * 100)46 (u128::from(available) * 100)
62 .checked_div(u128::from(total))47 .checked_div(u128::from(total))
63 .map(|p| u64::try_from(p).unwrap_or(100))48 .map(|p| u64::try_from(p).unwrap_or(100))
64 }49 }
65 50
66-/// Whether free space is below the configured floor: under `min_percent` of the total, or under
67-/// `min_gib` GiB when that is non-zero.
68 pub fn disk_is_low(total: u64, available: u64, min_percent: u64, min_gib: u64) -> bool {51 pub fn disk_is_low(total: u64, available: u64, min_percent: u64, min_gib: u64) -> bool {
69 let low_percent = free_percent(total, available).is_some_and(|p| p < min_percent);52 let low_percent = free_percent(total, available).is_some_and(|p| p < min_percent);
70 let low_gib = min_gib > 0 && available < min_gib.saturating_mul(1 << 30);53 let low_gib = min_gib > 0 && available < min_gib.saturating_mul(1 << 30);
71 low_percent || low_gib54 low_percent || low_gib
72 }55 }
73 56
74-/// Whether the newest successful backup is older than twice the schedule interval. A forge that
75-/// never made one counts from `since_unix`, when the alerting began.
76 pub fn backup_overdue(57 pub fn backup_overdue(
77 now_unix: i64,58 now_unix: i64,
78 last_ok_unix: Option<i64>,59 last_ok_unix: Option<i64>,
@@ -85,8 +66,6 @@ pub fn backup_overdue(
85 now_unix.saturating_sub(basis) > limit66 now_unix.saturating_sub(basis) > limit
86 }67 }
87 68
88-/// Whether a runner has been silent too long. `last_seen_unix` is `None` for one that never
89-/// checked in, which is not offline: it was never online.
90 pub fn runner_is_offline(now_unix: i64, last_seen_unix: Option<i64>, minutes: u64) -> bool {69 pub fn runner_is_offline(now_unix: i64, last_seen_unix: Option<i64>, minutes: u64) -> bool {
91 let limit = i64::try_from(minutes.saturating_mul(60)).unwrap_or(i64::MAX);70 let limit = i64::try_from(minutes.saturating_mul(60)).unwrap_or(i64::MAX);
92 last_seen_unix.is_some_and(|seen| now_unix.saturating_sub(seen) > limit)71 last_seen_unix.is_some_and(|seen| now_unix.saturating_sub(seen) > limit)
@@ -98,7 +77,6 @@ mod tests {
98 77
99 #[test]78 #[test]
100 fn kill_signatures_are_recognised_and_other_failures_are_not() {79 fn kill_signatures_are_recognised_and_other_failures_are_not() {
101- // (exit code, log tail, expected kill)
102 let cases: [(Option<i64>, Option<&str>, bool); 15] = [80 let cases: [(Option<i64>, Option<&str>, bool); 15] = [
103 (Some(137), None, true),81 (Some(137), None, true),
104 (Some(-9), None, true),82 (Some(-9), None, true),
crates/forge-core/src/audit.rsmodified+0 -15
@@ -1,7 +1,3 @@
1-//! Security audit log: the action names, the entry shape and the list filter. The stored shape is
2-//! in migrations/0010_audit_log.sql; the store functions live in store/audit.rs. Rows are never
3-//! edited; only the retention purge removes them.
4-
5 use ulid::Ulid;1 use ulid::Ulid;
6 2
7 use crate::time::now_stamp;3 use crate::time::now_stamp;
@@ -135,7 +131,6 @@ audit_actions! {
135 }131 }
136 132
137 impl AuditAction {133 impl AuditAction {
138- /// The action with this stored name, if any.
139 pub fn parse(name: &str) -> Option<AuditAction> {134 pub fn parse(name: &str) -> Option<AuditAction> {
140 AuditAction::ALL135 AuditAction::ALL
141 .iter()136 .iter()
@@ -144,7 +139,6 @@ impl AuditAction {
144 }139 }
145 }140 }
146 141
147-/// One row of the audit log. `at` is an RFC 3339 UTC stamp. `data` is a JSON object as text.
148 #[derive(Debug, Clone, PartialEq, Eq)]142 #[derive(Debug, Clone, PartialEq, Eq)]
149 pub struct AuditEntry {143 pub struct AuditEntry {
150 pub id: String,144 pub id: String,
@@ -160,7 +154,6 @@ pub struct AuditEntry {
160 }154 }
161 155
162 impl AuditEntry {156 impl AuditEntry {
163- /// A new entry stamped with the current time and a fresh id. Everything else is empty.
164 pub fn new(action: AuditAction) -> AuditEntry {157 pub fn new(action: AuditAction) -> AuditEntry {
165 AuditEntry {158 AuditEntry {
166 id: Ulid::generate().to_string(),159 id: Ulid::generate().to_string(),
@@ -177,22 +170,17 @@ impl AuditEntry {
177 }170 }
178 }171 }
179 172
180-/// Optional filters for [`crate::store::Store::list_audit`]. Unset fields do not restrict.
181 #[derive(Debug, Clone, Default, PartialEq, Eq)]173 #[derive(Debug, Clone, Default, PartialEq, Eq)]
182 pub struct AuditFilter {174 pub struct AuditFilter {
183 pub actor_id: Option<String>,175 pub actor_id: Option<String>,
184 pub action: Option<AuditAction>,176 pub action: Option<AuditAction>,
185 pub target_kind: Option<String>,177 pub target_kind: Option<String>,
186 pub target_id: Option<String>,178 pub target_id: Option<String>,
187- /// Matches entries where this user is the actor, or the `user` target.
188 pub involving_user: Option<String>,179 pub involving_user: Option<String>,
189- /// Entries stamped at or after this stamp.
190 pub since: Option<String>,180 pub since: Option<String>,
191- /// Entries stamped before this stamp.
192 pub until: Option<String>,181 pub until: Option<String>,
193 }182 }
194 183
195-/// Position in the newest-first listing: the last entry of the previous page.
196 #[derive(Debug, Clone, PartialEq, Eq)]184 #[derive(Debug, Clone, PartialEq, Eq)]
197 pub struct AuditCursor {185 pub struct AuditCursor {
198 pub at: String,186 pub at: String,
@@ -200,7 +188,6 @@ pub struct AuditCursor {
200 }188 }
201 189
202 impl AuditCursor {190 impl AuditCursor {
203- /// The cursor for the entry a page ended on.
204 pub fn after(entry: &AuditEntry) -> AuditCursor {191 pub fn after(entry: &AuditEntry) -> AuditCursor {
205 AuditCursor {192 AuditCursor {
206 at: entry.at.clone(),193 at: entry.at.clone(),
@@ -208,12 +195,10 @@ impl AuditCursor {
208 }195 }
209 }196 }
210 197
211- /// Text form for a URL: `<at>_<id>`. Neither part contains `_`.
212 pub fn encode(&self) -> String {198 pub fn encode(&self) -> String {
213 format!("{}_{}", self.at, self.id)199 format!("{}_{}", self.at, self.id)
214 }200 }
215 201
216- /// Parses [`AuditCursor::encode`] output. Anything malformed is `None`.
217 pub fn decode(text: &str) -> Option<AuditCursor> {202 pub fn decode(text: &str) -> Option<AuditCursor> {
218 let (at, id) = text.split_once('_')?;203 let (at, id) = text.split_once('_')?;
219 let stamp_ok = at.len() == 30 && at.ends_with('Z') && at.contains('T');204 let stamp_ok = at.len() == 30 && at.ends_with('Z') && at.contains('T');
crates/forge-core/src/authz.rsmodified+0 -24
@@ -1,40 +1,24 @@
1-//! Authorization rules. Pure, no IO.
2-
3 use crate::model::{Repo, Role, User, Visibility};1 use crate::model::{Repo, Role, User, Visibility};
4 2
5 #[derive(Debug, Clone, Copy, PartialEq, Eq)]3 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
6 pub enum Action {4 pub enum Action {
7 Read,5 Read,
8- /// Edit anyone's issue or comment, close/reopen, labels, assignees, milestones.
9- /// Not blocked by `archived` (the pages handle archived repos).
10 Triage,6 Triage,
11 Write,7 Write,
12 Admin,8 Admin,
13- /// Delete the repo. Owner and instance admin only; a collaborator role never grants it.
14 Delete,9 Delete,
15 }10 }
16 11
17-/// `NotFound` when the actor cannot even see the repo; `Forbidden` when they can see it but lack the right.
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 pub enum Denied {13 pub enum Denied {
20 NotFound,14 NotFound,
21 Forbidden,15 Forbidden,
22 }16 }
23 17
24-/// The higher of two optional roles. `Read < Triage < Write < Maintain < Admin`.
25 pub fn max_role(a: Option<Role>, b: Option<Role>) -> Option<Role> {18 pub fn max_role(a: Option<Role>, b: Option<Role>) -> Option<Role> {
26 a.max(b)19 a.max(b)
27 }20 }
28 21
29-/// Owner or instance admin: all actions. Public repo: Read for anyone.
30-/// Private repo with no role: NotFound. Read/Triage: Read. Write/Maintain: Read+Write. Admin: all.
31-/// Triage is granted to Triage, Write, Maintain and Admin.
32-/// Archived repos deny Write with Forbidden.
33-///
34-/// `org_role` is the role the actor gets through an organization that owns the repo (see
35-/// `Store::org_repo_role`). The effective role is `max_role(collaborator_role, org_role)`. A
36-/// collaborator Admin never deletes a repo; an org-derived Admin (org owner, or a team with
37-/// the admin role) does, because org-owned repos have no single owner person.
38 pub fn authorize(22 pub fn authorize(
39 actor: Option<&User>,23 actor: Option<&User>,
40 repo: &Repo,24 repo: &Repo,
@@ -42,7 +26,6 @@ pub fn authorize(
42 org_role: Option<Role>,26 org_role: Option<Role>,
43 action: Action,27 action: Action,
44 ) -> Result<(), Denied> {28 ) -> Result<(), Denied> {
45- // A role only belongs to a signed-in actor.
46 let role = if actor.is_some() {29 let role = if actor.is_some() {
47 max_role(collaborator_role, org_role)30 max_role(collaborator_role, org_role)
48 } else {31 } else {
@@ -140,7 +123,6 @@ mod tests {
140 }123 }
141 }124 }
142 125
143- /// Expected result from the contract, written independently of the implementation.
144 fn expected(126 fn expected(
145 actor: Option<&User>,127 actor: Option<&User>,
146 r: &Repo,128 r: &Repo,
@@ -155,7 +137,6 @@ mod tests {
155 return Ok(());137 return Ok(());
156 }138 }
157 if action == Action::Delete {139 if action == Action::Delete {
158- // Only owner or instance admin: hidden repos are 404, visible ones 403.
159 return if r.visibility == Visibility::Public || role.is_some() {140 return if r.visibility == Visibility::Public || role.is_some() {
160 Err(Denied::Forbidden)141 Err(Denied::Forbidden)
161 } else {142 } else {
@@ -393,7 +374,6 @@ mod tests {
393 authorize(Some(&root), &r, None, None, Action::Delete),374 authorize(Some(&root), &r, None, None, Action::Delete),
394 Ok(())375 Ok(())
395 );376 );
396- // A collaborator with the top role still cannot delete.
397 assert_eq!(377 assert_eq!(
398 authorize(Some(&stranger), &r, Some(Role::Admin), None, Action::Delete),378 authorize(Some(&stranger), &r, Some(Role::Admin), None, Action::Delete),
399 Err(Denied::Forbidden)379 Err(Denied::Forbidden)
@@ -407,7 +387,6 @@ mod tests {
407 }387 }
408 );388 );
409 }389 }
410- // Visible to a stranger on a public repo: 403. Hidden: 404.
411 let public = repo(Visibility::Public, false);390 let public = repo(Visibility::Public, false);
412 assert_eq!(391 assert_eq!(
413 authorize(Some(&stranger), &public, None, None, Action::Delete),392 authorize(Some(&stranger), &public, None, None, Action::Delete),
@@ -418,7 +397,6 @@ mod tests {
418 authorize(Some(&stranger), &private, None, None, Action::Delete),397 authorize(Some(&stranger), &private, None, None, Action::Delete),
419 Err(Denied::NotFound)398 Err(Denied::NotFound)
420 );399 );
421- // Archiving does not stop an owner from deleting.
422 let archived = repo(Visibility::Private, true);400 let archived = repo(Visibility::Private, true);
423 assert_eq!(401 assert_eq!(
424 authorize(Some(&owner), &archived, None, None, Action::Delete),402 authorize(Some(&owner), &archived, None, None, Action::Delete),
@@ -514,7 +492,6 @@ mod tests {
514 fn org_role_grants_what_the_collaborator_role_would() {492 fn org_role_grants_what_the_collaborator_role_would() {
515 let r = repo(Visibility::Private, false);493 let r = repo(Visibility::Private, false);
516 let member = user("member", false);494 let member = user("member", false);
517- // Read-only collaborator, but the org gives Write.
518 assert_eq!(495 assert_eq!(
519 authorize(496 authorize(
520 Some(&member),497 Some(&member),
@@ -525,7 +502,6 @@ mod tests {
525 ),502 ),
526 Ok(())503 Ok(())
527 );504 );
528- // An org role alone makes a private repo visible.
529 assert_eq!(505 assert_eq!(
530 authorize(Some(&member), &r, None, Some(Role::Read), Action::Read),506 authorize(Some(&member), &r, None, Some(Role::Read), Action::Read),
531 Ok(())507 Ok(())
crates/forge-core/src/avatar.rsmodified+0 -18
@@ -1,7 +1,3 @@
1-//! Avatar upload processing: validate, decode with limits, crop, resize and re-encode as PNG.
2-//!
3-//! Re-encoding to PNG drops all metadata (EXIF, GPS, comments) from the input.
4-
5 use std::io::Cursor;1 use std::io::Cursor;
6 2
7 use image::{ImageFormat, ImageReader, Limits, imageops::FilterType};3 use image::{ImageFormat, ImageReader, Limits, imageops::FilterType};
@@ -9,16 +5,12 @@ use sha2::{Digest, Sha256};
9 5
10 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
11 7
12-/// Largest accepted upload, in bytes.
13 pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024;8 pub const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024;
14 9
15-/// Largest accepted width or height of the decoded source image, in pixels.
16 const MAX_SOURCE_DIMENSION: u32 = 4096;10 const MAX_SOURCE_DIMENSION: u32 = 4096;
17 11
18-/// Upper bound on decoder allocations (128 MiB).
19 const MAX_ALLOC_BYTES: u64 = 128 * 1024 * 1024;12 const MAX_ALLOC_BYTES: u64 = 128 * 1024 * 1024;
20 13
21-/// Edge length of the stored avatar, in pixels.
22 const AVATAR_SIZE: u32 = 256;14 const AVATAR_SIZE: u32 = 256;
23 15
24 #[derive(Debug, Clone, PartialEq, Eq)]16 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -27,9 +19,6 @@ pub struct ProcessedAvatar {
27 pub hash: String,19 pub hash: String,
28 }20 }
29 21
30-/// Decode with limits (max 4096x4096, image::Limits), center-crop to a square, resize to 256x256
31-/// (Lanczos3), re-encode as PNG. Metadata (EXIF/GPS) is dropped by re-encoding. SVG, unknown
32-/// formats, too-large input or a decode failure give Error::Invalid.
33 pub fn process_avatar(bytes: &[u8]) -> Result<ProcessedAvatar> {22 pub fn process_avatar(bytes: &[u8]) -> Result<ProcessedAvatar> {
34 if bytes.len() > MAX_UPLOAD_BYTES {23 if bytes.len() > MAX_UPLOAD_BYTES {
35 return Err(Error::Invalid(format!(24 return Err(Error::Invalid(format!(
@@ -37,7 +26,6 @@ pub fn process_avatar(bytes: &[u8]) -> Result<ProcessedAvatar> {
37 )));26 )));
38 }27 }
39 28
40- // Format is decided from magic bytes only; the client-supplied type is never consulted.
41 let mut reader = ImageReader::new(Cursor::new(bytes))29 let mut reader = ImageReader::new(Cursor::new(bytes))
42 .with_guessed_format()30 .with_guessed_format()
43 .map_err(|_| Error::Invalid("unreadable image header".into()))?;31 .map_err(|_| Error::Invalid("unreadable image header".into()))?;
@@ -56,8 +44,6 @@ pub fn process_avatar(bytes: &[u8]) -> Result<ProcessedAvatar> {
56 limits.max_alloc = Some(MAX_ALLOC_BYTES);44 limits.max_alloc = Some(MAX_ALLOC_BYTES);
57 reader.limits(limits);45 reader.limits(limits);
58 46
59- // Center-crop to the largest square, then scale down to the avatar size. The decoded image
60- // (up to 128 MiB) is dropped as soon as the crop copies it, before the resize allocates.
61 let resized = {47 let resized = {
62 let decoded = reader48 let decoded = reader
63 .decode()49 .decode()
@@ -116,7 +102,6 @@ mod tests {
116 102
117 #[test]103 #[test]
118 fn accepted_inputs_become_256_png_avatars() {104 fn accepted_inputs_become_256_png_avatars() {
119- // (name, encoded input). Every accepted input yields a 256x256 PNG.
120 let cases = [105 let cases = [
121 ("png 300x200", encode(&sample(300, 200), ImageFormat::Png)),106 ("png 300x200", encode(&sample(300, 200), ImageFormat::Png)),
122 ("png 64x64", encode(&sample(64, 64), ImageFormat::Png)),107 ("png 64x64", encode(&sample(64, 64), ImageFormat::Png)),
@@ -157,10 +142,7 @@ mod tests {
157 142
158 #[test]143 #[test]
159 fn huge_declared_dimensions_are_rejected() {144 fn huge_declared_dimensions_are_rejected() {
160- // Take a valid tiny PNG and rewrite its IHDR to claim 50000x50000, fixing the CRC so
161- // only the dimension limit can reject it.
162 let mut png = encode(&sample(2, 2), ImageFormat::Png);145 let mut png = encode(&sample(2, 2), ImageFormat::Png);
163- // Layout: 8-byte signature, 4-byte length, 4-byte "IHDR", then width and height.
164 assert_eq!(&png[12..16], b"IHDR");146 assert_eq!(&png[12..16], b"IHDR");
165 png[16..20].copy_from_slice(&50_000u32.to_be_bytes());147 png[16..20].copy_from_slice(&50_000u32.to_be_bytes());
166 png[20..24].copy_from_slice(&50_000u32.to_be_bytes());148 png[20..24].copy_from_slice(&50_000u32.to_be_bytes());
crates/forge-core/src/cargo.rsmodified+0 -27
@@ -1,8 +1,3 @@
1-//! Cargo registry rules, pure and without IO: crate and version names, the publish body, the
2-//! index line written for each version, the index file path of a crate, and the README and
3-//! repository link found in a `.crate` file. The wire formats follow the Cargo book's registry
4-//! chapters: the publish body, the index format (version 2) and the sparse index layout.
5-
6 use std::io::Read;1 use std::io::Read;
7 2
8 use flate2::read::GzDecoder;3 use flate2::read::GzDecoder;
@@ -10,13 +5,9 @@ use serde_json::{Map, Value, json};
10 5
11 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
12 7
13-/// Longest crate name, in characters.
14 pub const MAX_NAME_CHARS: usize = 64;8 pub const MAX_NAME_CHARS: usize = 64;
15-/// Largest README read out of a `.crate` file, in bytes.
16 pub const MAX_README_BYTES: u64 = 256 * 1024;9 pub const MAX_README_BYTES: u64 = 256 * 1024;
17 10
18-/// Checks a crate name and returns its lowercase key. The key names the index file, so it is
19-/// what routes and storage use; the name as published is kept for display and the index.
20 pub fn crate_name_key(name: &str) -> Result<String> {11 pub fn crate_name_key(name: &str) -> Result<String> {
21 let starts_alpha = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic());12 let starts_alpha = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic());
22 let chars_ok = name13 let chars_ok = name
@@ -30,8 +21,6 @@ pub fn crate_name_key(name: &str) -> Result<String> {
30 Ok(name.to_ascii_lowercase())21 Ok(name.to_ascii_lowercase())
31 }22 }
32 23
33-/// The sparse index path of a crate key, relative to the index URL (`1/a`, `2/ab`, `3/a/abc`,
34-/// `ab/cd/abcdef`). The key is ASCII, checked by [`crate_name_key`].
35 pub fn index_path(key: &str) -> String {24 pub fn index_path(key: &str) -> String {
36 match key.len() {25 match key.len() {
37 1 => format!("1/{key}"),26 1 => format!("1/{key}"),
@@ -41,21 +30,16 @@ pub fn index_path(key: &str) -> String {
41 }30 }
42 }31 }
43 32
44-/// Parses a version as semver. Cargo versions are semver, with build metadata kept as written.
45 pub fn parse_version(version: &str) -> Result<semver::Version> {33 pub fn parse_version(version: &str) -> Result<semver::Version> {
46 semver::Version::parse(version)34 semver::Version::parse(version)
47 .map_err(|e| Error::Invalid(format!("`{version}` is not a valid version: {e}")))35 .map_err(|e| Error::Invalid(format!("`{version}` is not a valid version: {e}")))
48 }36 }
49 37
50-/// A publish body split into its parts. The metadata is the JSON document, the crate the
51-/// gzipped tarball whose sha256 the index records.
52 pub struct Publish<'a> {38 pub struct Publish<'a> {
53 pub metadata: Value,39 pub metadata: Value,
54 pub crate_file: &'a [u8],40 pub crate_file: &'a [u8],
55 }41 }
56 42
57-/// Splits a publish body: a little-endian u32 length and the JSON metadata, then a little-endian
58-/// u32 length and the `.crate` bytes. Both lengths must match the body exactly.
59 pub fn parse_publish(body: &[u8]) -> Result<Publish<'_>> {43 pub fn parse_publish(body: &[u8]) -> Result<Publish<'_>> {
60 let (json_len, rest) = take_len(body)?;44 let (json_len, rest) = take_len(body)?;
61 if json_len > rest.len() {45 if json_len > rest.len() {
@@ -92,13 +76,10 @@ fn take_len(bytes: &[u8]) -> Result<(usize, &[u8])> {
92 Ok((len, rest))76 Ok((len, rest))
93 }77 }
94 78
95-/// Text field of the metadata, or `None` when absent or not a string.
96 pub fn meta_str<'a>(meta: &'a Value, key: &str) -> Option<&'a str> {79 pub fn meta_str<'a>(meta: &'a Value, key: &str) -> Option<&'a str> {
97 meta.get(key).and_then(Value::as_str)80 meta.get(key).and_then(Value::as_str)
98 }81 }
99 82
100-/// The dependencies of an index line, from the publish metadata. A renamed dependency
101-/// (`explicit_name_in_toml`) is listed under its local name, with the real crate in `package`.
102 pub fn index_deps(meta: &Value) -> Vec<Value> {83 pub fn index_deps(meta: &Value) -> Vec<Value> {
103 let deps = meta.get("deps").and_then(Value::as_array);84 let deps = meta.get("deps").and_then(Value::as_array);
104 deps.map_or_else(Vec::new, |list| {85 deps.map_or_else(Vec::new, |list| {
@@ -122,8 +103,6 @@ pub fn index_deps(meta: &Value) -> Vec<Value> {
122 })103 })
123 }104 }
124 105
125-/// The index line of one version (format version 2). Features that use the `dep:` or `?`
126-/// syntax go to `features2`, as the format requires; the rest stay in `features`.
127 pub fn index_line(meta: &Value, checksum: &str) -> Result<Value> {106 pub fn index_line(meta: &Value, checksum: &str) -> Result<Value> {
128 let name =107 let name =
129 meta_str(meta, "name").ok_or_else(|| Error::Invalid("metadata has no name".into()))?;108 meta_str(meta, "name").ok_or_else(|| Error::Invalid("metadata has no name".into()))?;
@@ -164,8 +143,6 @@ pub fn index_line(meta: &Value, checksum: &str) -> Result<Value> {
164 Ok(line)143 Ok(line)
165 }144 }
166 145
167-/// The `(owner, repo)` a `repository` URL names on this forge, when it points at a repo under
168-/// `base_url` (for example `https://git.tahinli.com/`). Any other URL links nothing.
169 pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> {146 pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> {
170 let base = base_url.trim_end_matches('/');147 let base = base_url.trim_end_matches('/');
171 let rest = repository.trim().strip_prefix(base)?.strip_prefix('/')?;148 let rest = repository.trim().strip_prefix(base)?.strip_prefix('/')?;
@@ -180,12 +157,8 @@ pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> {
180 Some((owner.to_owned(), repo.to_owned()))157 Some((owner.to_owned(), repo.to_owned()))
181 }158 }
182 159
183-/// The README of a `.crate` file: the first `README*` file at the top of the package directory
184-/// (`<name>-<version>/README.md`). Read at most [`MAX_README_BYTES`] bytes. Returns `None` when
185-/// the archive is not a gzipped tarball or has no README.
186 pub fn crate_readme(crate_file: &[u8]) -> Option<String> {160 pub fn crate_readme(crate_file: &[u8]) -> Option<String> {
187 const MAX_INFLATED_SCAN_BYTES: u64 = 256 * 1024 * 1024;161 const MAX_INFLATED_SCAN_BYTES: u64 = 256 * 1024 * 1024;
188- // A small upload can inflate without end; past this much the README search gives up.
189 let inflated = GzDecoder::new(crate_file).take(MAX_INFLATED_SCAN_BYTES);162 let inflated = GzDecoder::new(crate_file).take(MAX_INFLATED_SCAN_BYTES);
190 let mut archive = tar::Archive::new(inflated);163 let mut archive = tar::Archive::new(inflated);
191 let entries = archive.entries().ok()?;164 let entries = archive.entries().ok()?;
crates/forge-core/src/ci.rsmodified+0 -98
@@ -1,9 +1,3 @@
1-//! CI models: run and job states, runners, runs, jobs and artifacts. The stored shape is in
2-//! migrations/0024_ci.sql; the store functions live in store/ci.rs.
3-//!
4-//! Job specs are kept as JSON text (`CiJob::spec_json`). The store reads only the `needs` and
5-//! `runs_on` arrays out of it.
6-
7 use std::collections::BTreeMap;1 use std::collections::BTreeMap;
8 use std::str::FromStr;2 use std::str::FromStr;
9 3
@@ -13,7 +7,6 @@ pub use forge_ci::proto::RestartMode;
13 7
14 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
15 9
16-/// State of a run. Stored as the `as_str` name.
17 #[derive(Debug, Clone, Copy, PartialEq, Eq)]10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18 pub enum RunState {11 pub enum RunState {
19 WaitingApproval,12 WaitingApproval,
@@ -38,7 +31,6 @@ impl RunState {
38 }31 }
39 }32 }
40 33
41- /// True for states a run cannot leave.
42 pub fn is_terminal(self) -> bool {34 pub fn is_terminal(self) -> bool {
43 matches!(35 matches!(
44 self,36 self,
@@ -64,7 +56,6 @@ impl FromStr for RunState {
64 }56 }
65 }57 }
66 58
67-/// State of a job. Stored as the `as_str` name.
68 #[derive(Debug, Clone, Copy, PartialEq, Eq)]59 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
69 pub enum JobState {60 pub enum JobState {
70 Blocked,61 Blocked,
@@ -91,7 +82,6 @@ impl JobState {
91 }82 }
92 }83 }
93 84
94- /// True for states a job cannot leave.
95 pub fn is_terminal(self) -> bool {85 pub fn is_terminal(self) -> bool {
96 matches!(86 matches!(
97 self,87 self,
@@ -122,7 +112,6 @@ impl FromStr for JobState {
122 }112 }
123 }113 }
124 114
125-/// A registered runner. The secret and its hash are never part of this type.
126 #[derive(Debug, Clone, PartialEq, Eq)]115 #[derive(Debug, Clone, PartialEq, Eq)]
127 pub struct CiRunner {116 pub struct CiRunner {
128 pub id: String,117 pub id: String,
@@ -131,50 +120,33 @@ pub struct CiRunner {
131 pub created_at: String,120 pub created_at: String,
132 pub last_seen_at: Option<String>,121 pub last_seen_at: Option<String>,
133 pub disabled: bool,122 pub disabled: bool,
134- /// The concurrency an admin set in the web UI (1 to 64). `None` means the runner uses the
135- /// value from its own `runner.toml`.
136 pub concurrency_override: Option<u32>,123 pub concurrency_override: Option<u32>,
137- /// What the runner last reported about itself. All `None` for a runner that never has.
138 pub reported: RunnerReport,124 pub reported: RunnerReport,
139- /// Jobs this runner is running now, counted from the job table.
140 pub running_jobs: u32,125 pub running_jobs: u32,
141- /// The runner's effective config as it last reported it, by field key. Secrets are redacted.
142 pub reported_config: BTreeMap<String, serde_json::Value>,126 pub reported_config: BTreeMap<String, serde_json::Value>,
143- /// A restart an admin asked for that the runner has not yet carried out.
144 pub restart: Option<RunnerRestart>,127 pub restart: Option<RunnerRestart>,
145- /// Admin-set values by field key. A key here beats the runner's own runner.toml.
146 pub config_overrides: BTreeMap<String, serde_json::Value>,128 pub config_overrides: BTreeMap<String, serde_json::Value>,
147 }129 }
148 130
149-/// A pending runner restart: asked for, not yet seen to happen.
150 #[derive(Debug, Clone, PartialEq, Eq)]131 #[derive(Debug, Clone, PartialEq, Eq)]
151 pub struct RunnerRestart {132 pub struct RunnerRestart {
152 pub mode: RestartMode,133 pub mode: RestartMode,
153 pub requested_at: String,134 pub requested_at: String,
154 }135 }
155 136
156-/// How a runner config field can be changed from the web UI.
157 #[derive(Debug, Clone, Copy, PartialEq, Eq)]137 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
158 pub enum FieldKind {138 pub enum FieldKind {
159- /// Applied on the runner's next check-in, with no restart.
160 Live,139 Live,
161- /// Stored now, applied when the runner next starts.
162 Restart,140 Restart,
163- /// Shown only.
164 ReadOnly,141 ReadOnly,
165 }142 }
166 143
167-/// One field of `runner.toml` as the admin UI sees it. `key` is the dotted TOML path.
168 #[derive(Debug, Clone, Copy)]144 #[derive(Debug, Clone, Copy)]
169 pub struct RunnerField {145 pub struct RunnerField {
170 pub key: &'static str,146 pub key: &'static str,
171 pub kind: FieldKind,147 pub kind: FieldKind,
172 }148 }
173 149
174-/// Every field the runner reports, in display order. Identity, the secret and the forge URL are
175-/// read-only: changing them from the forge would lock the runner out. Only `concurrency` and
176-/// `labels` can be applied without a restart, because the forge holds the labels itself and the
177-/// runner resizes its job slots live. Everything else is read once at startup.
178 pub const RUNNER_FIELDS: &[RunnerField] = &[150 pub const RUNNER_FIELDS: &[RunnerField] = &[
179 RunnerField {151 RunnerField {
180 key: "concurrency",152 key: "concurrency",
@@ -266,7 +238,6 @@ pub const RUNNER_FIELDS: &[RunnerField] = &[
266 },238 },
267 ];239 ];
268 240
269-/// The field with this key.
270 pub fn runner_field(key: &str) -> Option<&'static RunnerField> {241 pub fn runner_field(key: &str) -> Option<&'static RunnerField> {
271 RUNNER_FIELDS.iter().find(|f| f.key == key)242 RUNNER_FIELDS.iter().find(|f| f.key == key)
272 }243 }
@@ -283,8 +254,6 @@ fn int_in(
283 }254 }
284 }255 }
285 256
286-/// Checks `raw` (the text the admin typed) for field `key` and returns the JSON value to store.
287-/// `Err` carries a message for the admin. Read-only and unknown fields are refused.
288 pub fn validate_runner_field(257 pub fn validate_runner_field(
289 key: &str,258 key: &str,
290 raw: &str,259 raw: &str,
@@ -387,72 +356,46 @@ pub fn validate_runner_field(
387 }356 }
388 }357 }
389 358
390-/// Facts a runner reports about itself on a claim or heartbeat. A field the runner did not send is
391-/// `None` and leaves the stored value alone.
392 #[derive(Debug, Clone, Default, PartialEq, Eq)]359 #[derive(Debug, Clone, Default, PartialEq, Eq)]
393 pub struct RunnerReport {360 pub struct RunnerReport {
394- /// The concurrency the runner is applying right now.
395 pub concurrency: Option<u32>,361 pub concurrency: Option<u32>,
396 pub version: Option<String>,362 pub version: Option<String>,
397 pub cpus: Option<u32>,363 pub cpus: Option<u32>,
398 pub memory_bytes: Option<u64>,364 pub memory_bytes: Option<u64>,
399- /// The runner's build identity, like `0.1.0 (cf8e648, 2026-10-20)`.
400 pub build: Option<String>,365 pub build: Option<String>,
401- /// Random per process start. A change means the runner restarted.
402 pub boot_id: Option<String>,366 pub boot_id: Option<String>,
403- /// Features the runner says it has. The crate version never changes between builds, so the
404- /// forge gates features on these and not on the version.
405 pub capabilities: Vec<String>,367 pub capabilities: Vec<String>,
406- /// The runner's memory budget for jobs, in bytes.
407 pub memory_budget: Option<u64>,368 pub memory_budget: Option<u64>,
408- /// Budget minus what running jobs reserved, as of the runner's last claim.
409 pub memory_free: Option<u64>,369 pub memory_free: Option<u64>,
410- /// What the runner reserves for a job that declares no `memory`.
411 pub memory_reserve: Option<u64>,370 pub memory_reserve: Option<u64>,
412 }371 }
413 372
414 impl RunnerReport {373 impl RunnerReport {
415- /// Memory the running jobs reserved, when the runner reports a budget.
416 pub fn memory_reserved(&self) -> Option<u64> {374 pub fn memory_reserved(&self) -> Option<u64> {
417 Some(self.memory_budget?.saturating_sub(self.memory_free?))375 Some(self.memory_budget?.saturating_sub(self.memory_free?))
418 }376 }
419 }377 }
420 378
421-/// How long a queued job that does not fit a runner may wait before smaller jobs stop passing it.
422-/// See [`pick_by_memory`].
423 pub const STARVE_AFTER_SECS: u64 = 300;379 pub const STARVE_AFTER_SECS: u64 = 300;
424 380
425-/// What a runner can admit right now, from its claim.
426 #[derive(Debug, Clone, Copy, PartialEq, Eq)]381 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
427 pub struct MemoryOffer {382 pub struct MemoryOffer {
428- /// Budget minus what running jobs reserved, in bytes.
429 pub free: u64,383 pub free: u64,
430- /// The runner's whole budget. A job that reserves more than this is treated as reserving the
431- /// whole budget, so it still runs when the runner is idle instead of waiting forever.
432 pub budget: Option<u64>,384 pub budget: Option<u64>,
433- /// The reservation of a job that declares no `memory`.
434 pub default_reserve: u64,385 pub default_reserve: u64,
435 }386 }
436 387
437 impl MemoryOffer {388 impl MemoryOffer {
438- /// What a job reserves on this runner: its declared memory or the default, capped at the
439- /// budget.
440 pub fn reservation(&self, declared: Option<u64>) -> u64 {389 pub fn reservation(&self, declared: Option<u64>) -> u64 {
441 let want = declared.unwrap_or(self.default_reserve);390 let want = declared.unwrap_or(self.default_reserve);
442 self.budget.map_or(want, |budget| want.min(budget))391 self.budget.map_or(want, |budget| want.min(budget))
443 }392 }
444 393
445- /// True when a job with this declared memory fits in the free memory.
446 pub fn fits(&self, declared: Option<u64>) -> bool {394 pub fn fits(&self, declared: Option<u64>) -> bool {
447 self.reservation(declared) <= self.free395 self.reservation(declared) <= self.free
448 }396 }
449 }397 }
450 398
451-/// Picks which of the label-compatible queued jobs, oldest first, a runner with `offer` takes.
452-/// Each candidate is `(declared memory, seconds waited)`. Returns the index of the first job that
453-/// fits. A job that does not fit is skipped so smaller jobs behind it can run, but only while it
454-/// has waited less than `starve_after` seconds. Once an unfit job has waited that long, nothing
455-/// behind it is handed out: the runner drains its running jobs until the old job fits.
456 pub fn pick_by_memory(399 pub fn pick_by_memory(
457 candidates: &[(Option<u64>, u64)],400 candidates: &[(Option<u64>, u64)],
458 offer: &MemoryOffer,401 offer: &MemoryOffer,
@@ -469,24 +412,14 @@ pub fn pick_by_memory(
469 None412 None
470 }413 }
471 414
472-/// Why the queued jobs were not handed to one runner's claim. Counts only: nothing is claimed.
473 #[derive(Debug, Clone, Default, PartialEq, Eq)]415 #[derive(Debug, Clone, Default, PartialEq, Eq)]
474 pub struct QueueSkips {416 pub struct QueueSkips {
475- /// Queued jobs in all.
476 pub queued: usize,417 pub queued: usize,
477- /// Queued jobs whose `runs_on` names a label the runner lacks.
478 pub lacking_labels: usize,418 pub lacking_labels: usize,
479- /// The labels those jobs name that the runner lacks. Sorted, without repeats.
480 pub missing_labels: Vec<String>,419 pub missing_labels: Vec<String>,
481- /// Jobs the runner has the labels for but not the free memory. Only counted when the runner
482- /// offered its memory.
483 pub too_big: usize,420 pub too_big: usize,
484- /// The smallest reservation among the `too_big` jobs, in bytes.
485 pub smallest_need: Option<u64>,421 pub smallest_need: Option<u64>,
486- /// Jobs that fit but wait behind an older one that has starved (see [`pick_by_memory`]): the
487- /// runner takes nothing until that one fits.
488 pub held_behind: usize,422 pub held_behind: usize,
489- /// What the starved job reserves, in bytes, when one holds the queue.
490 pub starved_need: Option<u64>,423 pub starved_need: Option<u64>,
491 }424 }
492 425
@@ -494,23 +427,19 @@ fn size_in_range(raw: &str, lo: u64, hi: u64) -> bool {
494 forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n))427 forge_ci::size::parse_size(raw).is_some_and(|n| (lo..=hi).contains(&n))
495 }428 }
496 429
497-/// The capability of a runner that restarts when the forge asks.
498 pub const CAP_RESTART: &str = "restart";430 pub const CAP_RESTART: &str = "restart";
499 431
500 impl CiRunner {432 impl CiRunner {
501- /// True when the runner advertises that it honours a restart request.
502 pub fn supports_restart(&self) -> bool {433 pub fn supports_restart(&self) -> bool {
503 self.reported.capabilities.iter().any(|c| c == CAP_RESTART)434 self.reported.capabilities.iter().any(|c| c == CAP_RESTART)
504 }435 }
505 }436 }
506 437
507-/// One run of the workflow for a commit.
508 #[derive(Debug, Clone, PartialEq, Eq)]438 #[derive(Debug, Clone, PartialEq, Eq)]
509 pub struct CiRun {439 pub struct CiRun {
510 pub id: String,440 pub id: String,
511 pub repo_id: String,441 pub repo_id: String,
512 pub number: i64,442 pub number: i64,
513- /// `push`, `tag`, `pull_request` or `manual`.
514 pub trigger: String,443 pub trigger: String,
515 pub git_ref: String,444 pub git_ref: String,
516 pub commit_oid: String,445 pub commit_oid: String,
@@ -522,7 +451,6 @@ pub struct CiRun {
522 pub finished_at: Option<String>,451 pub finished_at: Option<String>,
523 }452 }
524 453
525-/// One job of a run. `spec_json` is the JobSpec as JSON text.
526 #[derive(Debug, Clone, PartialEq, Eq)]454 #[derive(Debug, Clone, PartialEq, Eq)]
527 pub struct CiJob {455 pub struct CiJob {
528 pub id: String,456 pub id: String,
@@ -539,40 +467,28 @@ pub struct CiJob {
539 pub heartbeat_at: Option<String>,467 pub heartbeat_at: Option<String>,
540 pub cancel_requested: bool,468 pub cancel_requested: bool,
541 pub log_bytes: i64,469 pub log_bytes: i64,
542- /// Processes the OOM killer took in the job's cgroup, as its runner reported. `None` when the
543- /// runner did not say (an older runner) or nothing was killed.
544 pub oom_kills: Option<u32>,470 pub oom_kills: Option<u32>,
545 }471 }
546 472
547-/// One job's duration in a recent successful run of a repo, for the CI time estimate. Only the
548-/// newest five successful runs per branch and per repo are sampled, so the ranks are 1 for the newest.
549 #[derive(Debug, Clone, PartialEq, Eq)]473 #[derive(Debug, Clone, PartialEq, Eq)]
550 pub struct JobSample {474 pub struct JobSample {
551 pub git_ref: String,475 pub git_ref: String,
552- /// The run's place among the repo's successful runs on its branch, newest first.
553 pub branch_rank: i64,476 pub branch_rank: i64,
554- /// The run's place among the repo's successful runs on any branch, newest first.
555 pub repo_rank: i64,477 pub repo_rank: i64,
556 pub job: String,478 pub job: String,
557- /// The job's duration in seconds.
558 pub secs: i64,479 pub secs: i64,
559 }480 }
560 481
561-/// A step of a job: a top-level `::group::` section of its log (migration 0071).
562 #[derive(Debug, Clone, PartialEq, Eq)]482 #[derive(Debug, Clone, PartialEq, Eq)]
563 pub struct JobStep {483 pub struct JobStep {
564 pub job_id: String,484 pub job_id: String,
565- /// The step's place in its job, from 0.
566 pub seq: i64,485 pub seq: i64,
567 pub name: String,486 pub name: String,
568 pub started_at: String,487 pub started_at: String,
569- /// Set when the group closed. Unset while it is open.
570 pub finished_at: Option<String>,488 pub finished_at: Option<String>,
571- /// Byte position of the group's line in the job's log.
572 pub log_offset: i64,489 pub log_offset: i64,
573 }490 }
574 491
575-/// What a step shows: its own state, or the job's once the job ended without closing it.
576 #[derive(Debug, Clone, Copy, PartialEq, Eq)]492 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
577 pub enum StepState {493 pub enum StepState {
578 Running,494 Running,
@@ -582,7 +498,6 @@ pub enum StepState {
582 }498 }
583 499
584 impl JobStep {500 impl JobStep {
585- /// A closed step passed. An open one follows its job: a job that succeeded passed it too.
586 pub fn state(&self, job: JobState) -> StepState {501 pub fn state(&self, job: JobState) -> StepState {
587 if self.finished_at.is_some() {502 if self.finished_at.is_some() {
588 return StepState::Passed;503 return StepState::Passed;
@@ -596,36 +511,24 @@ impl JobStep {
596 }511 }
597 }512 }
598 513
599-/// One step's duration in a recent successful run of a repo, for the CI time estimate. Sampled like
600-/// `JobSample`.
601 #[derive(Debug, Clone, PartialEq, Eq)]514 #[derive(Debug, Clone, PartialEq, Eq)]
602 pub struct StepSample {515 pub struct StepSample {
603 pub git_ref: String,516 pub git_ref: String,
604- /// The run's place among the repo's successful runs on its branch, newest first.
605 pub branch_rank: i64,517 pub branch_rank: i64,
606- /// The run's place among the repo's successful runs on any branch, newest first.
607 pub repo_rank: i64,518 pub repo_rank: i64,
608 pub job: String,519 pub job: String,
609 pub step: String,520 pub step: String,
610- /// The step's duration in seconds.
611 pub secs: i64,521 pub secs: i64,
612 }522 }
613 523
614-/// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The
615-/// run's page is `/{owner}/{repo}/ci/runs/{run_number}`.
616 #[derive(Debug, Clone, PartialEq, Eq)]524 #[derive(Debug, Clone, PartialEq, Eq)]
617 pub struct RunnerJob {525 pub struct RunnerJob {
618- /// The job itself.
619 pub job: CiJob,526 pub job: CiJob,
620- /// The number of the job's run, within its repo.
621 pub run_number: i64,527 pub run_number: i64,
622- /// The username of the repo's owner.
623 pub owner: String,528 pub owner: String,
624- /// The repo's name.
625 pub repo: String,529 pub repo: String,
626 }530 }
627 531
628-/// An artifact uploaded by a job. The file itself is stored outside the database.
629 #[derive(Debug, Clone, PartialEq, Eq)]532 #[derive(Debug, Clone, PartialEq, Eq)]
630 pub struct CiArtifact {533 pub struct CiArtifact {
631 pub id: String,534 pub id: String,
@@ -636,7 +539,6 @@ pub struct CiArtifact {
636 pub created_at: String,539 pub created_at: String,
637 }540 }
638 541
639-/// A job to create with a run. `needs` must match the `needs` in `spec_json`.
640 #[derive(Debug, Clone, Copy)]542 #[derive(Debug, Clone, Copy)]
641 pub struct NewJob<'a> {543 pub struct NewJob<'a> {
642 pub name: &'a str,544 pub name: &'a str,
crates/forge-core/src/config.rsmodified+0 -145
@@ -1,5 +1,3 @@
1-//! Instance configuration, read from TOML.
2-
3 use std::net::{IpAddr, SocketAddr};1 use std::net::{IpAddr, SocketAddr};
4 use std::path::{Path, PathBuf};2 use std::path::{Path, PathBuf};
5 3
@@ -16,7 +14,6 @@ pub enum Registration {
16 Open,14 Open,
17 }15 }
18 16
19-/// Parses each entry as a CIDR network or as a single address (a /32 or /128).
20 fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>(17 fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>(
21 deserializer: D,18 deserializer: D,
22 ) -> std::result::Result<Vec<IpNet>, D::Error> {19 ) -> std::result::Result<Vec<IpNet>, D::Error> {
@@ -45,14 +42,11 @@ fn default_user_content_listen() -> SocketAddr {
45 .expect("valid default socket address")42 .expect("valid default socket address")
46 }43 }
47 44
48-/// Outbound webhook delivery policy. Internal destinations are refused unless listed in `allowed_hosts`.
49 #[derive(Debug, Clone, Default, Deserialize)]45 #[derive(Debug, Clone, Default, Deserialize)]
50 #[serde(deny_unknown_fields)]46 #[serde(deny_unknown_fields)]
51 pub struct WebhookConfig {47 pub struct WebhookConfig {
52- /// Permit `http://` hook URLs in addition to `https://`.
53 #[serde(default)]48 #[serde(default)]
54 pub allow_http: bool,49 pub allow_http: bool,
55- /// Exact hostnames or CIDR networks that may be reached even when they resolve to internal addresses.
56 #[serde(default)]50 #[serde(default)]
57 pub allowed_hosts: Vec<String>,51 pub allowed_hosts: Vec<String>,
58 }52 }
@@ -65,70 +59,49 @@ pub struct Config {
65 pub listen: SocketAddr,59 pub listen: SocketAddr,
66 pub base_url: String,60 pub base_url: String,
67 pub user_content_base_url: String,61 pub user_content_base_url: String,
68- /// Listener that serves raw user files on the separate user-content origin.
69 #[serde(default = "default_user_content_listen")]62 #[serde(default = "default_user_content_listen")]
70 pub user_content_listen: SocketAddr,63 pub user_content_listen: SocketAddr,
71 pub ssh_listen: SocketAddr,64 pub ssh_listen: SocketAddr,
72 pub ssh_public_host: String,65 pub ssh_public_host: String,
73 pub ssh_public_port: u16,66 pub ssh_public_port: u16,
74- /// Seconds a failed SSH authentication waits before it is answered (brute-force damping).
75- /// Every SSH connection's first `none` probe fails, so this is paid per connection.
76 #[serde(default = "default_ssh_auth_rejection_secs")]67 #[serde(default = "default_ssh_auth_rejection_secs")]
77 pub ssh_auth_rejection_secs: u64,68 pub ssh_auth_rejection_secs: u64,
78 pub registration: Registration,69 pub registration: Registration,
79- /// Peers whose `X-Forwarded-For` header is trusted, such as the reverse proxy in front of forge.
80- /// Entries are addresses or CIDR networks. Empty by default, so the TCP peer is the client.
81 #[serde(default, deserialize_with = "deserialize_trusted_proxies")]70 #[serde(default, deserialize_with = "deserialize_trusted_proxies")]
82 pub trusted_proxies: Vec<IpNet>,71 pub trusted_proxies: Vec<IpNet>,
83- /// Outbound webhook policy, from the `[webhooks]` section.
84 #[serde(default)]72 #[serde(default)]
85 pub webhooks: WebhookConfig,73 pub webhooks: WebhookConfig,
86- /// Scheduled backups and fsck, from the `[backup]` section. An empty `dir` disables both.
87 #[serde(default)]74 #[serde(default)]
88 pub backup: BackupConfig,75 pub backup: BackupConfig,
89- /// Release asset limits, from the `[releases]` section.
90 #[serde(default)]76 #[serde(default)]
91 pub releases: ReleasesConfig,77 pub releases: ReleasesConfig,
92- /// Where release assets and CI artifacts are stored, from the `[storage]` section.
93 #[serde(default)]78 #[serde(default)]
94 pub storage: StorageConfig,79 pub storage: StorageConfig,
95- /// Standby replication, from the `[replication]` section. An empty `target` disables it.
96 #[serde(default)]80 #[serde(default)]
97 pub replication: ReplicationConfig,81 pub replication: ReplicationConfig,
98- /// Git LFS limits, from the `[lfs]` section.
99 #[serde(default)]82 #[serde(default)]
100 pub lfs: LfsConfig,83 pub lfs: LfsConfig,
101- /// CI limits and retention, from the `[ci]` section.
102 #[serde(default)]84 #[serde(default)]
103 pub ci: CiConfig,85 pub ci: CiConfig,
104- /// Security advisories (opt-in), from the `[advisories]` section.
105 #[serde(default)]86 #[serde(default)]
106 pub advisories: AdvisoriesConfig,87 pub advisories: AdvisoriesConfig,
107- /// Outgoing mail transport, from the `[mail]` section. The SMTP account is set in the database.
108 #[serde(default)]88 #[serde(default)]
109 pub mail: MailConfig,89 pub mail: MailConfig,
110- /// Organization rules, from the `[orgs]` section.
111 #[serde(default)]90 #[serde(default)]
112 pub orgs: OrgsConfig,91 pub orgs: OrgsConfig,
113- /// Self-update after a green CI run of the forge's own repo, from the `[self_update]` section.
114 #[serde(default)]92 #[serde(default)]
115 pub self_update: SelfUpdateConfig,93 pub self_update: SelfUpdateConfig,
116- /// Site announcement shown under every page header, from the `[banner]` section.
117 #[serde(default)]94 #[serde(default)]
118 pub banner: BannerConfig,95 pub banner: BannerConfig,
119- /// Alerts to site admins, from the `[alerts]` section.
120 #[serde(default)]96 #[serde(default)]
121 pub alerts: AlertsConfig,97 pub alerts: AlertsConfig,
122- /// Mirror sync timing, from the `[mirrors]` section.
123 #[serde(default)]98 #[serde(default)]
124 pub mirrors: MirrorsConfig,99 pub mirrors: MirrorsConfig,
125 }100 }
126 101
127-/// Mirror sync timing. The default is what production runs with; the e2e tests shorten it.
128 #[derive(Debug, Clone, Deserialize)]102 #[derive(Debug, Clone, Deserialize)]
129 #[serde(deny_unknown_fields, default)]103 #[serde(deny_unknown_fields, default)]
130 pub struct MirrorsConfig {104 pub struct MirrorsConfig {
131- /// Seconds a push mirror waits after the last ref update before it is sent.
132 pub push_debounce_secs: u64,105 pub push_debounce_secs: u64,
133 }106 }
134 107
@@ -140,21 +113,14 @@ impl Default for MirrorsConfig {
140 }113 }
141 }114 }
142 115
143-/// Admin alerts: what the forge tells the site admins about before something breaks.
144 #[derive(Debug, Clone, Deserialize)]116 #[derive(Debug, Clone, Deserialize)]
145 #[serde(deny_unknown_fields, default)]117 #[serde(deny_unknown_fields, default)]
146 pub struct AlertsConfig {118 pub struct AlertsConfig {
147- /// Master switch. Off sends nothing and raises nothing.
148 pub enabled: bool,119 pub enabled: bool,
149- /// Also email the admins, when they have a verified address and mail is set up.
150 pub email: bool,120 pub email: bool,
151- /// Minutes without a heartbeat before a runner counts as offline.
152 pub runner_offline_minutes: u64,121 pub runner_offline_minutes: u64,
153- /// Alert when the data directory has less than this percent free.
154 pub disk_free_percent: u64,122 pub disk_free_percent: u64,
155- /// Alert when the data directory has less than this many GiB free. 0 turns this check off.
156 pub disk_free_gib: u64,123 pub disk_free_gib: u64,
157- /// Per-kind switches.
158 pub on_runner_offline: bool,124 pub on_runner_offline: bool,
159 pub on_backup: bool,125 pub on_backup: bool,
160 pub on_disk: bool,126 pub on_disk: bool,
@@ -182,7 +148,6 @@ impl Default for AlertsConfig {
182 }148 }
183 149
184 impl AlertsConfig {150 impl AlertsConfig {
185- /// Whether alerts of `kind` are raised: the master switch and the kind's own switch.
186 pub fn kind_enabled(&self, kind: crate::alerts::AlertKind) -> bool {151 pub fn kind_enabled(&self, kind: crate::alerts::AlertKind) -> bool {
187 use crate::alerts::AlertKind as K;152 use crate::alerts::AlertKind as K;
188 self.enabled153 self.enabled
@@ -197,15 +162,11 @@ impl AlertsConfig {
197 }162 }
198 }163 }
199 164
200-/// Site announcement banner. An empty `message` shows nothing.
201 #[derive(Debug, Clone, Deserialize)]165 #[derive(Debug, Clone, Deserialize)]
202 #[serde(deny_unknown_fields, default)]166 #[serde(deny_unknown_fields, default)]
203 pub struct BannerConfig {167 pub struct BannerConfig {
204- /// One line of text. Empty turns the banner off.
205 pub message: String,168 pub message: String,
206- /// `info` or `warning`.
207 pub level: String,169 pub level: String,
208- /// UTC time as `YYYY-MM-DD HH:MM` after which the banner disappears. Empty for never.
209 pub expires: String,170 pub expires: String,
210 }171 }
211 172
@@ -220,18 +181,15 @@ impl Default for BannerConfig {
220 }181 }
221 182
222 impl BannerConfig {183 impl BannerConfig {
223- /// Unix seconds of `expires`, or `None` when unset or malformed.
224 pub fn expires_unix(&self) -> Option<i64> {184 pub fn expires_unix(&self) -> Option<i64> {
225 parse_banner_expiry(&self.expires)185 parse_banner_expiry(&self.expires)
226 }186 }
227 187
228- /// Whether the banner shows at `now` (unix seconds).
229 pub fn active_at(&self, now: i64) -> bool {188 pub fn active_at(&self, now: i64) -> bool {
230 !self.message.trim().is_empty() && self.expires_unix().is_none_or(|t| now < t)189 !self.message.trim().is_empty() && self.expires_unix().is_none_or(|t| now < t)
231 }190 }
232 }191 }
233 192
234-/// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds.
235 pub fn parse_banner_expiry(raw: &str) -> Option<i64> {193 pub fn parse_banner_expiry(raw: &str) -> Option<i64> {
236 let dt = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M", raw.trim()).ok()?;194 let dt = jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M", raw.trim()).ok()?;
237 if dt.year() < 1970 {195 if dt.year() < 1970 {
@@ -241,22 +199,13 @@ pub fn parse_banner_expiry(raw: &str) -> Option<i64> {
241 Some(zoned.timestamp().as_second())199 Some(zoned.timestamp().as_second())
242 }200 }
243 201
244-/// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo`
245-/// on `branch` replaces the running binary with the `artifact` of `job` and restarts.
246 #[derive(Debug, Clone, Deserialize)]202 #[derive(Debug, Clone, Deserialize)]
247 #[serde(deny_unknown_fields, default)]203 #[serde(deny_unknown_fields, default)]
248 pub struct SelfUpdateConfig {204 pub struct SelfUpdateConfig {
249- /// Whether a green run deploys its artifact. Off by default.
250 pub enabled: bool,205 pub enabled: bool,
251- /// The repo whose runs deploy, as `owner/name`.
252 pub repo: String,206 pub repo: String,
253- /// The branch whose push runs deploy.
254 pub branch: String,207 pub branch: String,
255- /// The CI job that produces the artifact.
256 pub job: String,208 pub job: String,
257- /// The artifact name produced by `job`. A single file. `{target}` is replaced with the
258- /// server's own `<arch>-<os>` target (e.g. `x86_64-linux`), so the same setting works on any
259- /// arch.
260 pub artifact: String,209 pub artifact: String,
261 }210 }
262 211
@@ -298,16 +247,12 @@ impl SelfUpdateConfig {
298 }247 }
299 }248 }
300 249
301-/// Organization rules, from the `[orgs]` section.
302 #[derive(Debug, Clone, Default, Deserialize)]250 #[derive(Debug, Clone, Default, Deserialize)]
303 #[serde(deny_unknown_fields, default)]251 #[serde(deny_unknown_fields, default)]
304 pub struct OrgsConfig {252 pub struct OrgsConfig {
305- /// Who may create an organization: `all` (any signed-in person, the default) or `admin`
306- /// (instance admins only).
307 pub creation: OrgCreation,253 pub creation: OrgCreation,
308 }254 }
309 255
310-/// Who may create organizations. See `OrgsConfig::creation`.
311 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]256 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
312 #[serde(rename_all = "lowercase")]257 #[serde(rename_all = "lowercase")]
313 pub enum OrgCreation {258 pub enum OrgCreation {
@@ -316,16 +261,12 @@ pub enum OrgCreation {
316 Admin,261 Admin,
317 }262 }
318 263
319-/// Outgoing mail transport, from the `[mail]` section. The SMTP server, sender and password are
320-/// set on `/admin/mail` and stored in the database; this section only picks the transport.
321 #[derive(Debug, Clone, Default, Deserialize)]264 #[derive(Debug, Clone, Default, Deserialize)]
322 #[serde(deny_unknown_fields, default)]265 #[serde(deny_unknown_fields, default)]
323 pub struct MailConfig {266 pub struct MailConfig {
324 pub transport: MailTransport,267 pub transport: MailTransport,
325 }268 }
326 269
327-/// `smtp` sends through the configured server. `log` writes each message to `<data_dir>/mail-log/`
328-/// instead, for development and tests.
329 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]270 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
330 #[serde(rename_all = "lowercase")]271 #[serde(rename_all = "lowercase")]
331 pub enum MailTransport {272 pub enum MailTransport {
@@ -334,33 +275,19 @@ pub enum MailTransport {
334 Log,275 Log,
335 }276 }
336 277
337-/// CI settings, from the `[ci]` section.
338 #[derive(Debug, Clone, Deserialize)]278 #[derive(Debug, Clone, Deserialize)]
339 #[serde(deny_unknown_fields, default)]279 #[serde(deny_unknown_fields, default)]
340 pub struct CiConfig {280 pub struct CiConfig {
341- /// Whether CI runs at all. When false, pushes and pull requests create no runs.
342 pub enabled: bool,281 pub enabled: bool,
343- /// Largest job log, in MiB. Past it the log is truncated.
344 pub max_log_mb: u64,282 pub max_log_mb: u64,
345- /// Largest artifact, in MiB.
346 pub max_artifact_mb: u64,283 pub max_artifact_mb: u64,
347- /// Artifacts a single job may upload.
348 pub max_artifacts_per_job: u32,284 pub max_artifacts_per_job: u32,
349- /// Largest total size of one job's artifacts, in MiB.
350 pub max_job_artifacts_mb: u64,285 pub max_job_artifacts_mb: u64,
351- /// Days a job log is kept.
352 pub log_retention_days: u64,286 pub log_retention_days: u64,
353- /// Days an artifact is kept.
354 pub artifact_retention_days: u64,287 pub artifact_retention_days: u64,
355- /// Artifacts of the newest this-many runs per repo (that have artifacts) are kept; older runs
356- /// lose theirs. 0 keeps all.
357 pub artifact_keep_runs: u32,288 pub artifact_keep_runs: u32,
358- /// Largest total size of all CI artifacts, in MiB. Past it, the oldest runs' artifacts are
359- /// deleted whole until the total fits. 0 is no limit.
360 pub artifact_max_total_mb: u64,289 pub artifact_max_total_mb: u64,
361- /// Hours a runner registration token stays valid.
362 pub registration_token_hours: u32,290 pub registration_token_hours: u32,
363- /// Milliseconds a runner claim waits for work before it is answered with no job.
364 pub claim_wait_ms: u64,291 pub claim_wait_ms: u64,
365 }292 }
366 293
@@ -382,16 +309,11 @@ impl Default for CiConfig {
382 }309 }
383 }310 }
384 311
385-/// Security advisories, from the `[advisories]` section. Off by default: when on, the forge
386-/// downloads the OSV dumps for `ecosystems` and scans each repo's lockfiles.
387 #[derive(Debug, Clone, Deserialize)]312 #[derive(Debug, Clone, Deserialize)]
388 #[serde(deny_unknown_fields, default)]313 #[serde(deny_unknown_fields, default)]
389 pub struct AdvisoriesConfig {314 pub struct AdvisoriesConfig {
390- /// Whether the advisory download and the lockfile scans run at all.
391 pub enabled: bool,315 pub enabled: bool,
392- /// OSV ecosystems to download and scan: any of `crates.io`, `npm`, `Go`.
393 pub ecosystems: Vec<String>,316 pub ecosystems: Vec<String>,
394- /// Hours before a downloaded dump is fetched again.
395 pub refresh_hours: u64,317 pub refresh_hours: u64,
396 }318 }
397 319
@@ -420,11 +342,9 @@ impl AdvisoriesConfig {
420 }342 }
421 }343 }
422 344
423-/// Git LFS limits, from the `[lfs]` section.
424 #[derive(Debug, Clone, Deserialize)]345 #[derive(Debug, Clone, Deserialize)]
425 #[serde(deny_unknown_fields, default)]346 #[serde(deny_unknown_fields, default)]
426 pub struct LfsConfig {347 pub struct LfsConfig {
427- /// Largest accepted LFS object, in MiB.
428 pub max_object_mb: u64,348 pub max_object_mb: u64,
429 }349 }
430 350
@@ -437,29 +357,20 @@ impl Default for LfsConfig {
437 }357 }
438 358
439 impl LfsConfig {359 impl LfsConfig {
440- /// The object size limit in bytes.
441 pub fn max_object_bytes(&self) -> u64 {360 pub fn max_object_bytes(&self) -> u64 {
442 self.max_object_mb.saturating_mul(1024 * 1024)361 self.max_object_mb.saturating_mul(1024 * 1024)
443 }362 }
444 }363 }
445 364
446-/// Standby replication, from the `[replication]` section. See `docs/backup.md`.
447 #[derive(Debug, Clone, Deserialize)]365 #[derive(Debug, Clone, Deserialize)]
448 #[serde(deny_unknown_fields, default)]366 #[serde(deny_unknown_fields, default)]
449 pub struct ReplicationConfig {367 pub struct ReplicationConfig {
450- /// `[user@]host:/absolute/base` of the standby account. Empty disables replication.
451 pub target: String,368 pub target: String,
452- /// SSH port of the standby host.
453 pub ssh_port: u16,369 pub ssh_port: u16,
454- /// Private key of the standby account (mode 0600). Required when `target` is set.
455 pub identity_file: PathBuf,370 pub identity_file: PathBuf,
456- /// Pinned host keys of the standby. Required when `target` is set; StrictHostKeyChecking is always `yes`.
457 pub known_hosts_file: PathBuf,371 pub known_hosts_file: PathBuf,
458- /// Minutes between database snapshots shipped to the standby.
459 pub db_snapshot_minutes: u64,372 pub db_snapshot_minutes: u64,
460- /// Minutes between reconcile passes (refs checksums, deleted repos, healthcheck).
461 pub reconcile_minutes: u64,373 pub reconcile_minutes: u64,
462- /// Optional URL pinged after each reconcile pass. Empty disables it.
463 pub healthcheck_url: String,374 pub healthcheck_url: String,
464 }375 }
465 376
@@ -478,7 +389,6 @@ impl Default for ReplicationConfig {
478 }389 }
479 390
480 impl ReplicationConfig {391 impl ReplicationConfig {
481- /// Whether the replication worker runs at all.
482 pub fn enabled(&self) -> bool {392 pub fn enabled(&self) -> bool {
483 !self.target.is_empty()393 !self.target.is_empty()
484 }394 }
@@ -511,11 +421,9 @@ impl ReplicationConfig {
511 }421 }
512 }422 }
513 423
514-/// Release settings, from the `[releases]` section.
515 #[derive(Debug, Clone, Deserialize)]424 #[derive(Debug, Clone, Deserialize)]
516 #[serde(deny_unknown_fields, default)]425 #[serde(deny_unknown_fields, default)]
517 pub struct ReleasesConfig {426 pub struct ReleasesConfig {
518- /// Largest accepted release asset, in mebibytes.
519 pub max_asset_mb: u64,427 pub max_asset_mb: u64,
520 }428 }
521 429
@@ -525,77 +433,48 @@ impl Default for ReleasesConfig {
525 }433 }
526 }434 }
527 435
528-/// Blob storage for release assets and CI artifacts, from the `[storage]` section. See
529-/// `docs/backup.md`. The default keeps blobs on the local disk under `<data_dir>/blobs`.
530 #[derive(Debug, Clone, Default, Deserialize)]436 #[derive(Debug, Clone, Default, Deserialize)]
531 #[serde(deny_unknown_fields, default)]437 #[serde(deny_unknown_fields, default)]
532 pub struct StorageConfig {438 pub struct StorageConfig {
533- /// `fs` (local disk, the default) or `s3` (any S3-compatible object store).
534 pub backend: StorageBackend,439 pub backend: StorageBackend,
535- /// Settings for `backend = "s3"`, from the `[storage.s3]` table. Ignored for `fs` and `r2`.
536 pub s3: S3Config,440 pub s3: S3Config,
537- /// Settings for `backend = "r2"`, from the `[storage.r2]` table. Ignored for `fs` and `s3`.
538 pub r2: R2Config,441 pub r2: R2Config,
539 }442 }
540 443
541-/// Blob backend. See `StorageConfig::backend`.
542 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]444 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
543 #[serde(rename_all = "lowercase")]445 #[serde(rename_all = "lowercase")]
544 pub enum StorageBackend {446 pub enum StorageBackend {
545 #[default]447 #[default]
546 Fs,448 Fs,
547 S3,449 S3,
548- /// Cloudflare R2, configured by account rather than by endpoint. See `R2Config`.
549 R2,450 R2,
550 }451 }
551 452
552-/// S3-compatible object store settings, from the `[storage.s3]` table. Works with AWS S3, MinIO,
553-/// Garage, Cloudflare R2 and similar. The secret is read from a file, so it stays out of this config.
554 #[derive(Debug, Clone, Default, Deserialize)]453 #[derive(Debug, Clone, Default, Deserialize)]
555 #[serde(deny_unknown_fields, default)]454 #[serde(deny_unknown_fields, default)]
556 pub struct S3Config {455 pub struct S3Config {
557- /// Bucket that holds the blobs. Required.
558 pub bucket: String,456 pub bucket: String,
559- /// Signing region, such as `eu-central-1`, or `auto` for R2. Required.
560 pub region: String,457 pub region: String,
561- /// Full URL of a non-AWS endpoint, such as `https://s3.example.internal:9000`. Empty uses AWS.
562 pub endpoint: String,458 pub endpoint: String,
563- /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root.
564 pub prefix: String,459 pub prefix: String,
565- /// Access key id. Required.
566 pub access_key_id: String,460 pub access_key_id: String,
567- /// File holding the secret access key (mode 0600). Its contents are trimmed. Required.
568 pub secret_access_key_file: PathBuf,461 pub secret_access_key_file: PathBuf,
569- /// Permit an `http://` endpoint. Only for a store on a trusted private network.
570 pub allow_http: bool,462 pub allow_http: bool,
571- /// Address buckets as subdomains (`bucket.host`) instead of paths (`host/bucket`). Path style is
572- /// the default because MinIO, Garage and most self-hosted stores expect it.
573 pub virtual_hosted_style: bool,463 pub virtual_hosted_style: bool,
574 }464 }
575 465
576-/// Cloudflare R2 settings, from the `[storage.r2]` table. The endpoint is derived from the account
577-/// id and jurisdiction, so the S3 wire details never appear in the config. The secret is read from
578-/// a file, as for `S3Config`.
579 #[derive(Debug, Clone, Default, Deserialize)]466 #[derive(Debug, Clone, Default, Deserialize)]
580 #[serde(deny_unknown_fields, default)]467 #[serde(deny_unknown_fields, default)]
581 pub struct R2Config {468 pub struct R2Config {
582- /// Cloudflare account id, the 32-character hex string from the dashboard. Required.
583 pub account_id: String,469 pub account_id: String,
584- /// Bucket that holds the blobs. Required.
585 pub bucket: String,470 pub bucket: String,
586- /// `""` (the default, global), `"eu"`, or `"fedramp"`. Must match the jurisdiction the bucket
587- /// was created in, or requests fail.
588 pub jurisdiction: String,471 pub jurisdiction: String,
589- /// Key prefix inside the bucket, such as `forge/`. Empty stores keys at the bucket root.
590 pub prefix: String,472 pub prefix: String,
591- /// Access key id of an R2 API token with object read and write. Required.
592 pub access_key_id: String,473 pub access_key_id: String,
593- /// File holding the secret access key (mode 0600). Its contents are trimmed. Required.
594 pub secret_access_key_file: PathBuf,474 pub secret_access_key_file: PathBuf,
595 }475 }
596 476
597 impl R2Config {477 impl R2Config {
598- /// The S3 API endpoint for this account and jurisdiction. Path-style, https only.
599 pub fn endpoint(&self) -> String {478 pub fn endpoint(&self) -> String {
600 match self.jurisdiction.as_str() {479 match self.jurisdiction.as_str() {
601 "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id),480 "" => format!("https://{}.r2.cloudflarestorage.com", self.account_id),
@@ -607,7 +486,6 @@ impl R2Config {
607 }486 }
608 }487 }
609 488
610-/// Fails unless `value` is non-empty after trimming. `section` names the table in the message.
611 fn require(section: &str, field: &str, value: &str) -> Result<()> {489 fn require(section: &str, field: &str, value: &str) -> Result<()> {
612 if value.trim().is_empty() {490 if value.trim().is_empty() {
613 return Err(Error::Config(format!(491 return Err(Error::Config(format!(
@@ -618,7 +496,6 @@ fn require(section: &str, field: &str, value: &str) -> Result<()> {
618 Ok(())496 Ok(())
619 }497 }
620 498
621-/// Checks that the secret file named by `[section]` exists and is a file.
622 fn check_secret_file(section: &str, path: &Path) -> Result<()> {499 fn check_secret_file(section: &str, path: &Path) -> Result<()> {
623 if path.as_os_str().is_empty() {500 if path.as_os_str().is_empty() {
624 return Err(Error::Config(format!(501 return Err(Error::Config(format!(
@@ -668,7 +545,6 @@ impl StorageConfig {
668 fn validate_r2(&self) -> Result<()> {545 fn validate_r2(&self) -> Result<()> {
669 let r2 = &self.r2;546 let r2 = &self.r2;
670 require("storage.r2", "account_id", &r2.account_id)?;547 require("storage.r2", "account_id", &r2.account_id)?;
671- // The account id becomes part of the host name, so only hex digits are allowed.
672 if !r2.account_id.chars().all(|c| c.is_ascii_hexdigit()) {548 if !r2.account_id.chars().all(|c| c.is_ascii_hexdigit()) {
673 return Err(Error::Config(549 return Err(Error::Config(
674 "[storage.r2] account_id must contain only hex digits (copy it from the Cloudflare dashboard)".into(),550 "[storage.r2] account_id must contain only hex digits (copy it from the Cloudflare dashboard)".into(),
@@ -687,19 +563,13 @@ impl StorageConfig {
687 }563 }
688 }564 }
689 565
690-/// Scheduled backups, from the `[backup]` section. See `docs/backup.md`.
691 #[derive(Debug, Clone, Deserialize)]566 #[derive(Debug, Clone, Deserialize)]
692 #[serde(deny_unknown_fields, default)]567 #[serde(deny_unknown_fields, default)]
693 pub struct BackupConfig {568 pub struct BackupConfig {
694- /// Directory that receives the backup sets. Empty disables the scheduler.
695 pub dir: PathBuf,569 pub dir: PathBuf,
696- /// Hours between full backup sets.
697 pub interval_hours: u64,570 pub interval_hours: u64,
698- /// Newest complete sets kept in `dir`. Older complete sets are deleted after a good run.
699 pub keep: usize,571 pub keep: usize,
700- /// Optional healthchecks.io style URL. Pinged with `/start`, then the URL itself or `/fail`.
701 pub healthcheck_url: String,572 pub healthcheck_url: String,
702- /// Days between `git fsck` and integrity checks of every repo and the database.
703 pub fsck_interval_days: u64,573 pub fsck_interval_days: u64,
704 }574 }
705 575
@@ -716,7 +586,6 @@ impl Default for BackupConfig {
716 }586 }
717 587
718 impl BackupConfig {588 impl BackupConfig {
719- /// Whether the scheduler runs at all.
720 pub fn enabled(&self) -> bool {589 pub fn enabled(&self) -> bool {
721 !self.dir.as_os_str().is_empty()590 !self.dir.as_os_str().is_empty()
722 }591 }
@@ -739,7 +608,6 @@ impl BackupConfig {
739 }608 }
740 }609 }
741 610
742-/// Development defaults, written when the config file is missing. Keep in sync with `config/forge.example.toml`.
743 const DEV_DEFAULTS: &str = r#"# forge configuration (development defaults). Production values belong in /etc/forge/forge.toml.611 const DEV_DEFAULTS: &str = r#"# forge configuration (development defaults). Production values belong in /etc/forge/forge.toml.
744 612
745 # SQLite/Turso database file.613 # SQLite/Turso database file.
@@ -766,13 +634,10 @@ trusted_proxies = []
766 "#;634 "#;
767 635
768 impl Config {636 impl Config {
769- /// Loads the config from `path`. Writes development defaults if the file is missing.
770 pub fn load(path: &Path) -> Result<Config> {637 pub fn load(path: &Path) -> Result<Config> {
771 Self::load_with_keys(path).map(|(config, _)| config)638 Self::load_with_keys(path).map(|(config, _)| config)
772 }639 }
773 640
774- /// Like `load`, and also returns the dotted keys the file sets (such as `ci.max_log_mb`), so the
775- /// settings page can tell a file value from a default.
776 pub fn load_with_keys(path: &Path) -> Result<(Config, std::collections::BTreeSet<String>)> {641 pub fn load_with_keys(path: &Path) -> Result<(Config, std::collections::BTreeSet<String>)> {
777 let text = match std::fs::read_to_string(path) {642 let text = match std::fs::read_to_string(path) {
778 Ok(text) => text,643 Ok(text) => text,
@@ -795,8 +660,6 @@ impl Config {
795 Ok((config, keys))660 Ok((config, keys))
796 }661 }
797 662
798- /// The cross-field rules the loader applies after parsing. The settings page runs the same
799- /// check before it stores an override.
800 pub fn validate(&self) -> Result<()> {663 pub fn validate(&self) -> Result<()> {
801 self.backup.validate()?;664 self.backup.validate()?;
802 self.replication.validate()?;665 self.replication.validate()?;
@@ -807,7 +670,6 @@ impl Config {
807 }670 }
808 }671 }
809 672
810-/// Collects the dotted path of every non-table value in `table`.
811 fn flatten_keys(prefix: &str, table: &toml::Table, out: &mut std::collections::BTreeSet<String>) {673 fn flatten_keys(prefix: &str, table: &toml::Table, out: &mut std::collections::BTreeSet<String>) {
812 for (key, value) in table {674 for (key, value) in table {
813 let path = if prefix.is_empty() {675 let path = if prefix.is_empty() {
@@ -840,7 +702,6 @@ mod tests {
840 assert_eq!(cfg.ssh_listen, "0.0.0.0:2222".parse().unwrap());702 assert_eq!(cfg.ssh_listen, "0.0.0.0:2222".parse().unwrap());
841 assert_eq!(cfg.ssh_public_port, 2222);703 assert_eq!(cfg.ssh_public_port, 2222);
842 assert_eq!(cfg.registration, Registration::Closed);704 assert_eq!(cfg.registration, Registration::Closed);
843- // Reloading the written file gives the same config.
844 let again = Config::load(&path).unwrap();705 let again = Config::load(&path).unwrap();
845 assert_eq!(again.base_url, cfg.base_url);706 assert_eq!(again.base_url, cfg.base_url);
846 }707 }
@@ -957,13 +818,11 @@ mod tests {
957 let path = dir.path().join("forge.toml");818 let path = dir.path().join("forge.toml");
958 std::fs::write(&path, DEV_DEFAULTS).unwrap();819 std::fs::write(&path, DEV_DEFAULTS).unwrap();
959 let cfg = Config::load(&path).unwrap();820 let cfg = Config::load(&path).unwrap();
960- // backup
961 assert!(!cfg.backup.enabled(), "backup enabled");821 assert!(!cfg.backup.enabled(), "backup enabled");
962 assert_eq!(cfg.backup.interval_hours, 24, "backup interval");822 assert_eq!(cfg.backup.interval_hours, 24, "backup interval");
963 assert_eq!(cfg.backup.keep, 7, "backup keep");823 assert_eq!(cfg.backup.keep, 7, "backup keep");
964 assert_eq!(cfg.backup.fsck_interval_days, 7, "backup fsck");824 assert_eq!(cfg.backup.fsck_interval_days, 7, "backup fsck");
965 assert!(cfg.backup.healthcheck_url.is_empty(), "backup healthcheck");825 assert!(cfg.backup.healthcheck_url.is_empty(), "backup healthcheck");
966- // replication
967 assert!(!cfg.replication.enabled(), "replication enabled");826 assert!(!cfg.replication.enabled(), "replication enabled");
968 assert_eq!(cfg.replication.ssh_port, 22, "replication ssh port");827 assert_eq!(cfg.replication.ssh_port, 22, "replication ssh port");
969 assert_eq!(828 assert_eq!(
@@ -978,7 +837,6 @@ mod tests {
978 cfg.replication.healthcheck_url.is_empty(),837 cfg.replication.healthcheck_url.is_empty(),
979 "replication healthcheck"838 "replication healthcheck"
980 );839 );
981- // self_update
982 assert!(!cfg.self_update.enabled, "self_update enabled");840 assert!(!cfg.self_update.enabled, "self_update enabled");
983 assert_eq!(cfg.self_update.branch, "main", "self_update branch");841 assert_eq!(cfg.self_update.branch, "main", "self_update branch");
984 assert_eq!(cfg.self_update.job, "build", "self_update job");842 assert_eq!(cfg.self_update.job, "build", "self_update job");
@@ -986,7 +844,6 @@ mod tests {
986 cfg.self_update.artifact, "forge-{target}",844 cfg.self_update.artifact, "forge-{target}",
987 "self_update artifact"845 "self_update artifact"
988 );846 );
989- // storage
990 assert_eq!(cfg.storage.backend, StorageBackend::Fs, "storage backend");847 assert_eq!(cfg.storage.backend, StorageBackend::Fs, "storage backend");
991 assert!(cfg.storage.s3.bucket.is_empty(), "s3 bucket");848 assert!(cfg.storage.s3.bucket.is_empty(), "s3 bucket");
992 assert!(!cfg.storage.s3.allow_http, "s3 allow_http");849 assert!(!cfg.storage.s3.allow_http, "s3 allow_http");
@@ -1129,7 +986,6 @@ mod tests {
1129 assert!(Config::load(&path).is_ok());986 assert!(Config::load(&path).is_ok());
1130 }987 }
1131 988
1132- /// A complete `[storage.r2]` table with a real secret file, minus any lines the caller drops.
1133 fn r2_config_text(dir: &Path, drop: &[&str], extra: &str) -> String {989 fn r2_config_text(dir: &Path, drop: &[&str], extra: &str) -> String {
1134 let secret = dir.join("r2-secret");990 let secret = dir.join("r2-secret");
1135 std::fs::write(&secret, "r2s3cret\n").unwrap();991 std::fs::write(&secret, "r2s3cret\n").unwrap();
@@ -1186,7 +1042,6 @@ mod tests {
1186 let dir = tempfile::tempdir().unwrap();1042 let dir = tempfile::tempdir().unwrap();
1187 let path = dir.path().join("forge.toml");1043 let path = dir.path().join("forge.toml");
1188 let absent = dir.path().join("absent").display().to_string();1044 let absent = dir.path().join("absent").display().to_string();
1189- // (label, lines to drop from the complete table, extra lines, expected to load)
1190 let cases: Vec<(&str, &[&str], String, bool)> = vec![1045 let cases: Vec<(&str, &[&str], String, bool)> = vec![
1191 ("complete", &[], String::new(), true),1046 ("complete", &[], String::new(), true),
1192 ("account_id missing", &["account_id"], String::new(), false),1047 ("account_id missing", &["account_id"], String::new(), false),
crates/forge-core/src/discussions.rsmodified+0 -23
@@ -1,19 +1,13 @@
1-//! Discussion types: a per-repo forum next to issues. Storage lives in `store/discussions.rs`.
2-//! Titles and bodies are checked with the issue validators, since the limits are the same.
3-
4 use crate::error::{Error, Result};1 use crate::error::{Error, Result};
5 2
6-/// Categories a discussion can be filed under. The `as_str` names are stored.
7 #[derive(Debug, Clone, Copy, PartialEq, Eq)]3 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
8 pub enum DiscussionCategory {4 pub enum DiscussionCategory {
9 General,5 General,
10 Ideas,6 Ideas,
11 Qa,7 Qa,
12- /// Only Maintain or higher may post here.
13 Announcements,8 Announcements,
14 }9 }
15 10
16-/// Every category, in the order the chooser shows them.
17 pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[11 pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[
18 DiscussionCategory::General,12 DiscussionCategory::General,
19 DiscussionCategory::Ideas,13 DiscussionCategory::Ideas,
@@ -22,7 +16,6 @@ pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[
22 ];16 ];
23 17
24 impl DiscussionCategory {18 impl DiscussionCategory {
25- /// The stored and URL name.
26 pub fn as_str(self) -> &'static str {19 pub fn as_str(self) -> &'static str {
27 match self {20 match self {
28 DiscussionCategory::General => "general",21 DiscussionCategory::General => "general",
@@ -32,7 +25,6 @@ impl DiscussionCategory {
32 }25 }
33 }26 }
34 27
35- /// The label people read.
36 pub fn label(self) -> &'static str {28 pub fn label(self) -> &'static str {
37 match self {29 match self {
38 DiscussionCategory::General => "General",30 DiscussionCategory::General => "General",
@@ -42,7 +34,6 @@ impl DiscussionCategory {
42 }34 }
43 }35 }
44 36
45- /// The category with this stored name, if any.
46 pub fn parse(name: &str) -> Option<DiscussionCategory> {37 pub fn parse(name: &str) -> Option<DiscussionCategory> {
47 DISCUSSION_CATEGORIES38 DISCUSSION_CATEGORIES
48 .iter()39 .iter()
@@ -51,7 +42,6 @@ impl DiscussionCategory {
51 }42 }
52 }43 }
53 44
54-/// One discussion. `answer_comment_id` is set only in Q&A, and names the accepted reply.
55 #[derive(Debug, Clone, PartialEq, Eq)]45 #[derive(Debug, Clone, PartialEq, Eq)]
56 pub struct Discussion {46 pub struct Discussion {
57 pub id: String,47 pub id: String,
@@ -68,24 +58,19 @@ pub struct Discussion {
68 pub updated_at: String,58 pub updated_at: String,
69 }59 }
70 60
71-/// A discussion with its author's username, for the list.
72 #[derive(Debug, Clone, PartialEq, Eq)]61 #[derive(Debug, Clone, PartialEq, Eq)]
73 pub struct DiscussionListItem {62 pub struct DiscussionListItem {
74 pub discussion: Discussion,63 pub discussion: Discussion,
75 pub author: String,64 pub author: String,
76 }65 }
77 66
78-/// Why a discussion is in a user's inbox. The `as_str` names are stored in `discussion_notifications`.
79 #[derive(Debug, Clone, Copy, PartialEq, Eq)]67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
80 pub enum DiscussionReason {68 pub enum DiscussionReason {
81- /// The user was @mentioned in the discussion or one of its comments.
82 Mention,69 Mention,
83- /// Someone commented on the user's discussion.
84 Reply,70 Reply,
85 }71 }
86 72
87 impl DiscussionReason {73 impl DiscussionReason {
88- /// The stored name.
89 pub fn as_str(self) -> &'static str {74 pub fn as_str(self) -> &'static str {
90 match self {75 match self {
91 DiscussionReason::Mention => "mention",76 DiscussionReason::Mention => "mention",
@@ -93,7 +78,6 @@ impl DiscussionReason {
93 }78 }
94 }79 }
95 80
96- /// The reason with this stored name, if any.
97 pub fn parse(name: &str) -> Option<DiscussionReason> {81 pub fn parse(name: &str) -> Option<DiscussionReason> {
98 match name {82 match name {
99 "mention" => Some(DiscussionReason::Mention),83 "mention" => Some(DiscussionReason::Mention),
@@ -103,7 +87,6 @@ impl DiscussionReason {
103 }87 }
104 }88 }
105 89
106-/// One inbox row for a discussion, joined with its repo and title for the notifications page.
107 #[derive(Debug, Clone, PartialEq, Eq)]90 #[derive(Debug, Clone, PartialEq, Eq)]
108 pub struct DiscussionNotification {91 pub struct DiscussionNotification {
109 pub discussion_id: String,92 pub discussion_id: String,
@@ -113,14 +96,11 @@ pub struct DiscussionNotification {
113 pub number: i64,96 pub number: i64,
114 pub title: String,97 pub title: String,
115 pub reason: DiscussionReason,98 pub reason: DiscussionReason,
116- /// Username of the last person who acted, if the account still exists.
117 pub last_actor_name: Option<String>,99 pub last_actor_name: Option<String>,
118 pub unread: bool,100 pub unread: bool,
119 pub updated_at: String,101 pub updated_at: String,
120 }102 }
121 103
122-/// One comment. A top-level comment has no `parent_id`; a reply names a top-level comment of the
123-/// same discussion. A deleted comment has `deleted` set and an empty body.
124 #[derive(Debug, Clone, PartialEq, Eq)]104 #[derive(Debug, Clone, PartialEq, Eq)]
125 pub struct DiscussionComment {105 pub struct DiscussionComment {
126 pub id: String,106 pub id: String,
@@ -133,7 +113,6 @@ pub struct DiscussionComment {
133 pub deleted: bool,113 pub deleted: bool,
134 }114 }
135 115
136-/// Filters and paging for the discussion list. `category: None` lists every category.
137 #[derive(Debug, Clone, PartialEq, Eq)]116 #[derive(Debug, Clone, PartialEq, Eq)]
138 pub struct DiscussionFilter {117 pub struct DiscussionFilter {
139 pub category: Option<DiscussionCategory>,118 pub category: Option<DiscussionCategory>,
@@ -141,14 +120,12 @@ pub struct DiscussionFilter {
141 pub per_page: u32,120 pub per_page: u32,
142 }121 }
143 122
144-/// Validates a discussion title (trimmed, returned) and body.
145 pub fn validate_discussion(title: &str, body: &str) -> Result<String> {123 pub fn validate_discussion(title: &str, body: &str) -> Result<String> {
146 let title = crate::issues::validate_title(title)?;124 let title = crate::issues::validate_title(title)?;
147 crate::issues::validate_body(body)?;125 crate::issues::validate_body(body)?;
148 Ok(title)126 Ok(title)
149 }127 }
150 128
151-/// Validates a comment body: not blank, and within the body limit.
152 pub fn validate_comment(body: &str) -> Result<()> {129 pub fn validate_comment(body: &str) -> Result<()> {
153 crate::issues::validate_body(body)?;130 crate::issues::validate_body(body)?;
154 if body.trim().is_empty() {131 if body.trim().is_empty() {
crates/forge-core/src/error.rsmodified+0 -2
@@ -1,5 +1,3 @@
1-//! The error type shared across forge crates.
2-
3 #[derive(Debug, thiserror::Error)]1 #[derive(Debug, thiserror::Error)]
4 pub enum Error {2 pub enum Error {
5 #[error("io error: {0}")]3 #[error("io error: {0}")]
crates/forge-core/src/issue_refs.rsmodified+0 -20
@@ -1,30 +1,15 @@
1-//! Parsing of issue references (`#12`) and closing keywords (`fixes #12`) in free text.
2-//! Hand-written scanner, no regex. Pure, no IO.
3-
4 use std::ops::Range;1 use std::ops::Range;
5 2
6-/// Keywords that close an issue when followed by a `#N` reference. Compared case-insensitively.
7 const CLOSING_KEYWORDS: [&str; 9] = [3 const CLOSING_KEYWORDS: [&str; 9] = [
8 "close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved",4 "close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved",
9 ];5 ];
10 6
11-/// Maximum number of digits in an issue number.
12 const MAX_DIGITS: usize = 9;7 const MAX_DIGITS: usize = 9;
13 8
14-/// Every `#N` reference in `text`, deduplicated, in order of first appearance.
15-///
16-/// A reference is `#` followed by 1 to 9 digits. It is not recognised when the `#` is preceded by
17-/// an alphanumeric char, `&` or `/`, or when the digits are followed by an alphanumeric char.
18-/// `#0` is not an issue number and is ignored.
19 pub fn find_issue_refs(text: &str) -> Vec<i64> {9 pub fn find_issue_refs(text: &str) -> Vec<i64> {
20 dedup(issue_ref_spans(text).into_iter().map(|(_, n)| n))10 dedup(issue_ref_spans(text).into_iter().map(|(_, n)| n))
21 }11 }
22 12
23-/// Issue numbers closed by closing keywords in `text`, deduplicated, in order.
24-///
25-/// The keyword (case-insensitive, whole word) must directly precede the reference, optionally
26-/// separated by a `:`, with at least one whitespace char between the keyword (or colon) and `#`.
27-/// Example: `"Fixes: #3, closes #4"` gives `[3, 4]`; `"unfixes #2"` gives nothing.
28 pub fn find_closing_refs(text: &str) -> Vec<i64> {13 pub fn find_closing_refs(text: &str) -> Vec<i64> {
29 dedup(14 dedup(
30 issue_ref_spans(text)15 issue_ref_spans(text)
@@ -44,8 +29,6 @@ fn dedup(values: impl Iterator<Item = i64>) -> Vec<i64> {
44 out29 out
45 }30 }
46 31
47-/// Byte range (including the `#`) and value of every valid `#N` reference in `text`, in order.
48-/// Duplicates are kept. Used to link references in rendered markdown with the same rules.
49 pub fn issue_ref_spans(text: &str) -> Vec<(Range<usize>, i64)> {32 pub fn issue_ref_spans(text: &str) -> Vec<(Range<usize>, i64)> {
50 let bytes = text.as_bytes();33 let bytes = text.as_bytes();
51 let mut refs = Vec::new();34 let mut refs = Vec::new();
@@ -86,12 +69,9 @@ pub fn issue_ref_spans(text: &str) -> Vec<(Range<usize>, i64)> {
86 refs69 refs
87 }70 }
88 71
89-/// True when `before` (the text preceding a `#N` reference) ends with a closing keyword,
90-/// an optional `:`, and at least one whitespace char.
91 fn preceded_by_closing_keyword(before: &str) -> bool {72 fn preceded_by_closing_keyword(before: &str) -> bool {
92 let trimmed = before.trim_end();73 let trimmed = before.trim_end();
93 if trimmed.len() == before.len() {74 if trimmed.len() == before.len() {
94- // No whitespace between the keyword and the reference.
95 return false;75 return false;
96 }76 }
97 let word_part = trimmed.strip_suffix(':').unwrap_or(trimmed);77 let word_part = trimmed.strip_suffix(':').unwrap_or(trimmed);
crates/forge-core/src/issues.rsmodified+0 -32
@@ -1,18 +1,10 @@
1-//! Issue, comment, label and milestone types, and their validation. Stored shapes are in
2-//! migrations/0004_issues.sql; the store functions live in store/issues.rs and store/labels.rs.
3-
4 use crate::error::{Error, Result};1 use crate::error::{Error, Result};
5 use crate::model::Id;2 use crate::model::Id;
6 3
7-/// Longest accepted issue title, in characters.
8 pub const MAX_TITLE: usize = 256;4 pub const MAX_TITLE: usize = 256;
9-/// Largest accepted issue, comment or edit body, in bytes.
10 pub const MAX_BODY: usize = 65536;5 pub const MAX_BODY: usize = 65536;
11-/// Longest accepted label name, in characters.
12 pub const MAX_LABEL_NAME: usize = 50;6 pub const MAX_LABEL_NAME: usize = 50;
13-/// Longest label description, in characters.
14 pub const MAX_LABEL_DESCRIPTION: usize = 500;7 pub const MAX_LABEL_DESCRIPTION: usize = 500;
15-/// Most assignees one issue can have.
16 pub const MAX_ASSIGNEES: usize = 10;8 pub const MAX_ASSIGNEES: usize = 10;
17 9
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -84,13 +76,10 @@ pub struct Issue {
84 pub created_at: String,76 pub created_at: String,
85 pub updated_at: String,77 pub updated_at: String,
86 pub closed_at: Option<String>,78 pub closed_at: Option<String>,
87- /// Locked conversations accept writes only from collaborators with Triage or higher.
88 pub locked: bool,79 pub locked: bool,
89- /// One of `LOCK_REASONS`, or `None` when no reason was given.
90 pub lock_reason: Option<String>,80 pub lock_reason: Option<String>,
91 }81 }
92 82
93-/// Reasons accepted when locking a conversation.
94 pub const LOCK_REASONS: &[&str] = &["off_topic", "too_heated", "resolved", "spam"];83 pub const LOCK_REASONS: &[&str] = &["off_topic", "too_heated", "resolved", "spam"];
95 84
96 #[derive(Debug, Clone, PartialEq)]85 #[derive(Debug, Clone, PartialEq)]
@@ -108,7 +97,6 @@ pub struct Comment {
108 pub struct IssueEvent {97 pub struct IssueEvent {
109 pub id: Id,98 pub id: Id,
110 pub issue_id: Id,99 pub issue_id: Id,
111- /// `None` for system events.
112 pub actor_id: Option<Id>,100 pub actor_id: Option<Id>,
113 pub kind: String,101 pub kind: String,
114 pub data: serde_json::Value,102 pub data: serde_json::Value,
@@ -120,7 +108,6 @@ pub struct Label {
120 pub id: Id,108 pub id: Id,
121 pub repo_id: Id,109 pub repo_id: Id,
122 pub name: String,110 pub name: String,
123- /// Lowercase `#rrggbb`.
124 pub color: String,111 pub color: String,
125 pub description: String,112 pub description: String,
126 }113 }
@@ -131,12 +118,10 @@ pub struct Milestone {
131 pub repo_id: Id,118 pub repo_id: Id,
132 pub title: String,119 pub title: String,
133 pub description: String,120 pub description: String,
134- /// `YYYY-MM-DD` or `None`.
135 pub due_on: Option<String>,121 pub due_on: Option<String>,
136 pub state: IssueState,122 pub state: IssueState,
137 pub created_at: String,123 pub created_at: String,
138 pub closed_at: Option<String>,124 pub closed_at: Option<String>,
139- /// Counts filled by list/get queries.
140 pub open_issues: i64,125 pub open_issues: i64,
141 pub closed_issues: i64,126 pub closed_issues: i64,
142 }127 }
@@ -144,22 +129,14 @@ pub struct Milestone {
144 #[derive(Debug, Clone, PartialEq)]129 #[derive(Debug, Clone, PartialEq)]
145 pub struct IssueFilter {130 pub struct IssueFilter {
146 pub state: Option<IssueState>,131 pub state: Option<IssueState>,
147- /// Label name.
148 pub label: Option<String>,132 pub label: Option<String>,
149- /// Milestone title.
150 pub milestone: Option<String>,133 pub milestone: Option<String>,
151- /// Author username.
152 pub author: Option<String>,134 pub author: Option<String>,
153- /// Assignee username.
154 pub assignee: Option<String>,135 pub assignee: Option<String>,
155- /// Username with a pending review request (pull requests only).
156 pub review_requested: Option<String>,136 pub review_requested: Option<String>,
157- /// Substring of the title, case-insensitive.
158 pub query: Option<String>,137 pub query: Option<String>,
159- /// Pull requests only: `Some(true)` lists drafts, `Some(false)` lists ready pull requests.
160 pub draft: Option<bool>,138 pub draft: Option<bool>,
161 pub sort: IssueSort,139 pub sort: IssueSort,
162- /// 1-based.
163 pub page: u32,140 pub page: u32,
164 pub per_page: u32,141 pub per_page: u32,
165 }142 }
@@ -191,7 +168,6 @@ pub enum IssueSort {
191 }168 }
192 169
193 impl IssueSort {170 impl IssueSort {
194- /// The value used in the `sort` query parameter.
195 pub fn as_str(&self) -> &'static str {171 pub fn as_str(&self) -> &'static str {
196 match self {172 match self {
197 IssueSort::Newest => "newest",173 IssueSort::Newest => "newest",
@@ -217,14 +193,11 @@ impl std::str::FromStr for IssueSort {
217 #[derive(Debug, Clone, PartialEq)]193 #[derive(Debug, Clone, PartialEq)]
218 pub struct IssueListItem {194 pub struct IssueListItem {
219 pub issue: Issue,195 pub issue: Issue,
220- /// Display username of the author.
221 pub author: String,196 pub author: String,
222 pub labels: Vec<Label>,197 pub labels: Vec<Label>,
223- /// Display usernames of the assignees.
224 pub assignees: Vec<String>,198 pub assignees: Vec<String>,
225 }199 }
226 200
227-/// Trimmed title: non-empty, at most `MAX_TITLE` characters, no control characters.
228 pub fn validate_title(t: &str) -> Result<String> {201 pub fn validate_title(t: &str) -> Result<String> {
229 let title = t.trim();202 let title = t.trim();
230 if title.is_empty() {203 if title.is_empty() {
@@ -241,7 +214,6 @@ pub fn validate_title(t: &str) -> Result<String> {
241 Ok(title.to_string())214 Ok(title.to_string())
242 }215 }
243 216
244-/// Body: at most `MAX_BODY` bytes. An empty body is allowed.
245 pub fn validate_body(b: &str) -> Result<()> {217 pub fn validate_body(b: &str) -> Result<()> {
246 if b.len() > MAX_BODY {218 if b.len() > MAX_BODY {
247 return Err(Error::Invalid(format!(219 return Err(Error::Invalid(format!(
@@ -251,8 +223,6 @@ pub fn validate_body(b: &str) -> Result<()> {
251 Ok(())223 Ok(())
252 }224 }
253 225
254-/// Returns `(trimmed name, normalized color)`. The name is 1..=50 characters with no control
255-/// characters. The color is `#rgb` or `#rrggbb` in any case and comes back as lowercase `#rrggbb`.
256 pub fn validate_label(name: &str, color: &str, description: &str) -> Result<(String, String)> {226 pub fn validate_label(name: &str, color: &str, description: &str) -> Result<(String, String)> {
257 let name = name.trim();227 let name = name.trim();
258 let len = name.chars().count();228 let len = name.chars().count();
@@ -310,7 +280,6 @@ mod tests {
310 assert!(validate_title("a\nb").is_err());280 assert!(validate_title("a\nb").is_err());
311 assert!(validate_title(&"x".repeat(MAX_TITLE)).is_ok());281 assert!(validate_title(&"x".repeat(MAX_TITLE)).is_ok());
312 assert!(validate_title(&"x".repeat(MAX_TITLE + 1)).is_err());282 assert!(validate_title(&"x".repeat(MAX_TITLE + 1)).is_err());
313- // Counted in characters, not bytes.
314 assert!(validate_title(&"é".repeat(MAX_TITLE)).is_ok());283 assert!(validate_title(&"é".repeat(MAX_TITLE)).is_ok());
315 assert!(validate_title(&"é".repeat(MAX_TITLE + 1)).is_err());284 assert!(validate_title(&"é".repeat(MAX_TITLE + 1)).is_err());
316 }285 }
@@ -320,7 +289,6 @@ mod tests {
320 assert!(validate_body("").is_ok());289 assert!(validate_body("").is_ok());
321 assert!(validate_body(&"x".repeat(MAX_BODY)).is_ok());290 assert!(validate_body(&"x".repeat(MAX_BODY)).is_ok());
322 assert!(validate_body(&"x".repeat(MAX_BODY + 1)).is_err());291 assert!(validate_body(&"x".repeat(MAX_BODY + 1)).is_err());
323- // 2 bytes per char: 32768 chars is exactly MAX_BODY bytes.
324 assert!(validate_body(&"é".repeat(MAX_BODY / 2)).is_ok());292 assert!(validate_body(&"é".repeat(MAX_BODY / 2)).is_ok());
325 assert!(validate_body(&"é".repeat(MAX_BODY / 2 + 1)).is_err());293 assert!(validate_body(&"é".repeat(MAX_BODY / 2 + 1)).is_err());
326 }294 }
crates/forge-core/src/lfs_token.rsmodified+0 -17
@@ -1,8 +1,3 @@
1-//! Short-lived signed tokens for Git LFS transfer actions.
2-//!
3-//! Token format: `"<expires>.<op>.<base64url-nopad(hmac_sha256)>"`, where the MAC covers
4-//! `"lfs\0" + repo_id + "\0" + op + "\0" + expires`. `op` is `download`, `upload` or `any`.
5-
6 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};1 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
7 use hmac::{Hmac, KeyInit, Mac};2 use hmac::{Hmac, KeyInit, Mac};
8 use sha2::Sha256;3 use sha2::Sha256;
@@ -12,7 +7,6 @@ type HmacSha256 = Hmac<Sha256>;
12 7
13 const MAC_LEN: usize = 32;8 const MAC_LEN: usize = 32;
14 9
15-/// The operation a token grants. `Any` grants both download and upload.
16 #[derive(Debug, Clone, Copy, PartialEq, Eq)]10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
17 pub enum LfsOp {11 pub enum LfsOp {
18 Download,12 Download,
@@ -40,7 +34,6 @@ impl LfsOp {
40 }34 }
41 35
42 fn mac_for(key: &[u8; 32], repo_id: &str, op: &str, expires_unix: i64) -> HmacSha256 {36 fn mac_for(key: &[u8; 32], repo_id: &str, op: &str, expires_unix: i64) -> HmacSha256 {
43- // HMAC accepts keys of any length, so construction with a 32-byte key cannot fail.
44 let mut mac =37 let mut mac =
45 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");38 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");
46 mac.update(b"lfs\0");39 mac.update(b"lfs\0");
@@ -52,7 +45,6 @@ fn mac_for(key: &[u8; 32], repo_id: &str, op: &str, expires_unix: i64) -> HmacSh
52 mac45 mac
53 }46 }
54 47
55-/// Issues a token for `repo_id`, valid for `op` until `expires_unix` (seconds since the epoch).
56 pub fn issue(key: &[u8; 32], repo_id: &str, op: LfsOp, expires_unix: i64) -> String {48 pub fn issue(key: &[u8; 32], repo_id: &str, op: LfsOp, expires_unix: i64) -> String {
57 let tag = mac_for(key, repo_id, op.as_str(), expires_unix)49 let tag = mac_for(key, repo_id, op.as_str(), expires_unix)
58 .finalize()50 .finalize()
@@ -64,11 +56,6 @@ pub fn issue(key: &[u8; 32], repo_id: &str, op: LfsOp, expires_unix: i64) -> Str
64 )56 )
65 }57 }
66 58
67-/// Verifies `token` for `repo_id` and the wanted operation at time `now_unix`.
68-///
69-/// Rejects malformed input, expired tokens (`now >= expires`) and bad MACs. The MAC
70-/// comparison is constant time. An `Any` token satisfies `Download` and `Upload`; a
71-/// `Download` token never satisfies `Upload`, and only an `Any` token satisfies `Any`.
72 pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_unix: i64) -> bool {59 pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_unix: i64) -> bool {
73 let mut parts = token.splitn(3, '.');60 let mut parts = token.splitn(3, '.');
74 let (Some(expires_str), Some(op_str), Some(mac_str)) =61 let (Some(expires_str), Some(op_str), Some(mac_str)) =
@@ -76,7 +63,6 @@ pub fn verify(key: &[u8; 32], token: &str, repo_id: &str, wanted: LfsOp, now_uni
76 else {63 else {
77 return false;64 return false;
78 };65 };
79- // Strict canonical decimal: no sign, no leading zeros, no whitespace.
80 let Ok(expires) = expires_str.parse::<i64>() else {66 let Ok(expires) = expires_str.parse::<i64>() else {
81 return false;67 return false;
82 };68 };
@@ -178,14 +164,11 @@ mod tests {
178 #[test]164 #[test]
179 fn tampering_is_rejected() {165 fn tampering_is_rejected() {
180 let token = issue(&KEY, "repo-1", LfsOp::Download, NOW + 60);166 let token = issue(&KEY, "repo-1", LfsOp::Download, NOW + 60);
181- // Upgrading the op in the clear must fail the MAC check.
182 let upgraded = token.replacen(".download.", ".any.", 1);167 let upgraded = token.replacen(".download.", ".any.", 1);
183 assert!(!verify(&KEY, &upgraded, "repo-1", LfsOp::Upload, NOW));168 assert!(!verify(&KEY, &upgraded, "repo-1", LfsOp::Upload, NOW));
184- // Extending expiry must fail too.
185 let (exp, rest) = token.split_once('.').unwrap();169 let (exp, rest) = token.split_once('.').unwrap();
186 let extended = format!("{}.{rest}", exp.parse::<i64>().unwrap() + 1000);170 let extended = format!("{}.{rest}", exp.parse::<i64>().unwrap() + 1000);
187 assert!(!verify(&KEY, &extended, "repo-1", LfsOp::Download, NOW));171 assert!(!verify(&KEY, &extended, "repo-1", LfsOp::Download, NOW));
188- // Flipping a MAC character must fail.
189 let mut bytes = token.into_bytes();172 let mut bytes = token.into_bytes();
190 let last = bytes.len() - 1;173 let last = bytes.len() - 1;
191 bytes[last] = if bytes[last] == b'A' { b'B' } else { b'A' };174 bytes[last] = if bytes[last] == b'A' { b'B' } else { b'A' };
crates/forge-core/src/lib.rsmodified+0 -2
@@ -1,5 +1,3 @@
1-//! Domain types, storage, configuration and security primitives for forge.
2-
3 pub mod advisories;1 pub mod advisories;
4 pub mod alerts;2 pub mod alerts;
5 pub mod audit;3 pub mod audit;
crates/forge-core/src/mail.rsmodified+0 -33
@@ -1,13 +1,8 @@
1-//! Outgoing mail: the SMTP settings, the outbox states, the retry schedule and the send error.
2-//! The store functions live in store/mail.rs; the transports live in forge-web (mail/).
3-
4 use std::fmt;1 use std::fmt;
5 use std::time::Duration;2 use std::time::Duration;
6 3
7-/// Tries per message: one first try and five retries. Once the last try fails, the message gives up.
8 pub const MAX_ATTEMPTS: u32 = 6;4 pub const MAX_ATTEMPTS: u32 = 6;
9 5
10-/// The wait after the first, second, ... failed try. Five waits serve five retries.
11 const BACKOFF: [Duration; 5] = [6 const BACKOFF: [Duration; 5] = [
12 Duration::from_secs(60),7 Duration::from_secs(60),
13 Duration::from_secs(5 * 60),8 Duration::from_secs(5 * 60),
@@ -16,7 +11,6 @@ const BACKOFF: [Duration; 5] = [
16 Duration::from_secs(12 * 60 * 60),11 Duration::from_secs(12 * 60 * 60),
17 ];12 ];
18 13
19-/// The wait before the next try, given that `attempts` tries have failed. `None` means give up.
20 pub fn retry_delay(attempts: u32) -> Option<Duration> {14 pub fn retry_delay(attempts: u32) -> Option<Duration> {
21 if attempts == 0 || attempts >= MAX_ATTEMPTS {15 if attempts == 0 || attempts >= MAX_ATTEMPTS {
22 return None;16 return None;
@@ -24,14 +18,10 @@ pub fn retry_delay(attempts: u32) -> Option<Duration> {
24 BACKOFF.get((attempts - 1) as usize).copied()18 BACKOFF.get((attempts - 1) as usize).copied()
25 }19 }
26 20
27-/// How the SMTP connection is secured.
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 pub enum Security {22 pub enum Security {
30- /// Plain connection upgraded with STARTTLS (port 587 usually).
31 StartTls,23 StartTls,
32- /// TLS from the first byte (port 465 usually).
33 Tls,24 Tls,
34- /// No encryption. Only for a relay on a trusted network.
35 Plain,25 Plain,
36 }26 }
37 27
@@ -54,8 +44,6 @@ impl Security {
54 }44 }
55 }45 }
56 46
57-/// The stored SMTP settings. The password is never part of this value; `has_password` says whether
58-/// one is stored.
59 #[derive(Debug, Clone, PartialEq, Eq)]47 #[derive(Debug, Clone, PartialEq, Eq)]
60 pub struct MailSettings {48 pub struct MailSettings {
61 pub host: String,49 pub host: String,
@@ -69,7 +57,6 @@ pub struct MailSettings {
69 pub updated_at: Option<String>,57 pub updated_at: Option<String>,
70 }58 }
71 59
72-/// A change to the SMTP settings. `password: None` keeps the stored password; `Some` replaces it.
73 pub struct MailSettingsUpdate<'a> {60 pub struct MailSettingsUpdate<'a> {
74 pub host: &'a str,61 pub host: &'a str,
75 pub port: u16,62 pub port: u16,
@@ -96,7 +83,6 @@ impl fmt::Debug for MailSettingsUpdate<'_> {
96 }83 }
97 }84 }
98 85
99-/// The decrypted SMTP password. Its Debug output is redacted.
100 #[derive(Clone, PartialEq, Eq)]86 #[derive(Clone, PartialEq, Eq)]
101 pub struct MailPassword(String);87 pub struct MailPassword(String);
102 88
@@ -116,7 +102,6 @@ impl fmt::Debug for MailPassword {
116 }102 }
117 }103 }
118 104
119-/// What a message is for. The queue page shows it, and the account page reads the latest one.
120 #[derive(Debug, Clone, Copy, PartialEq, Eq)]105 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
121 pub enum MailKind {106 pub enum MailKind {
122 Verification,107 Verification,
@@ -153,19 +138,13 @@ impl MailKind {
153 }138 }
154 }139 }
155 140
156-/// Where a queued message stands at one moment. Derived from the outbox row, never stored.
157 #[derive(Debug, Clone, Copy, PartialEq, Eq)]141 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
158 pub enum MailState {142 pub enum MailState {
159- /// Waiting for its first try.
160 Queued,143 Queued,
161- /// A try failed; the next one is scheduled.
162 Retrying,144 Retrying,
163- /// Leased by a worker pass and being sent now.
164 Sending,145 Sending,
165 Sent,146 Sent,
166- /// The last try failed (or the error was permanent). Nothing more is scheduled.
167 Failed,147 Failed,
168- /// A failed message an admin gave up on by hand.
169 Discarded,148 Discarded,
170 }149 }
171 150
@@ -195,18 +174,14 @@ impl MailState {
195 }174 }
196 }175 }
197 176
198-/// One message to send. Its Debug output omits the body, which can carry one-time links.
199 #[derive(Clone, PartialEq, Eq)]177 #[derive(Clone, PartialEq, Eq)]
200 pub struct OutgoingMail {178 pub struct OutgoingMail {
201 pub to: String,179 pub to: String,
202 pub subject: String,180 pub subject: String,
203 pub body: String,181 pub body: String,
204- /// `Message-ID` header, in `<...>` form. `None` for mail that is not part of a thread.
205 pub message_id: Option<String>,182 pub message_id: Option<String>,
206- /// `In-Reply-To` and `References` headers, in `<...>` form.
207 pub in_reply_to: Option<String>,183 pub in_reply_to: Option<String>,
208 pub kind: MailKind,184 pub kind: MailKind,
209- /// The account the message is about. `None` for mail with no account yet.
210 pub user_id: Option<String>,185 pub user_id: Option<String>,
211 }186 }
212 187
@@ -221,7 +196,6 @@ impl fmt::Debug for OutgoingMail {
221 }196 }
222 }197 }
223 198
224-/// One outbox row. The body is kept for the worker; the admin list never shows it.
225 #[derive(Clone, PartialEq, Eq)]199 #[derive(Clone, PartialEq, Eq)]
226 pub struct OutboxEntry {200 pub struct OutboxEntry {
227 pub id: String,201 pub id: String,
@@ -234,10 +208,8 @@ pub struct OutboxEntry {
234 pub kind: MailKind,208 pub kind: MailKind,
235 pub user_id: Option<String>,209 pub user_id: Option<String>,
236 pub created_at: String,210 pub created_at: String,
237- /// Tries made so far.
238 pub attempts: u32,211 pub attempts: u32,
239 pub next_attempt_at: Option<String>,212 pub next_attempt_at: Option<String>,
240- /// Set while a worker pass holds the row. Past this stamp the lease is void.
241 pub lease_until: Option<String>,213 pub lease_until: Option<String>,
242 pub sent_at: Option<String>,214 pub sent_at: Option<String>,
243 pub discarded_at: Option<String>,215 pub discarded_at: Option<String>,
@@ -260,19 +232,16 @@ impl fmt::Debug for OutboxEntry {
260 }232 }
261 }233 }
262 234
263-/// The latest message of one kind for one account, as the account page shows it.
264 #[derive(Debug, Clone, PartialEq, Eq)]235 #[derive(Debug, Clone, PartialEq, Eq)]
265 pub struct MailStatus {236 pub struct MailStatus {
266 pub state: MailState,237 pub state: MailState,
267 pub created_at: String,238 pub created_at: String,
268- /// Tries made so far, failed ones included.
269 pub attempts: u32,239 pub attempts: u32,
270 pub sent_at: Option<String>,240 pub sent_at: Option<String>,
271 pub last_error: Option<String>,241 pub last_error: Option<String>,
272 }242 }
273 243
274 impl OutboxEntry {244 impl OutboxEntry {
275- /// The state of the row at `now` (an RFC 3339-style stamp, compared as text).
276 pub fn state_at(&self, now: &str) -> MailState {245 pub fn state_at(&self, now: &str) -> MailState {
277 if self.sent_at.is_some() {246 if self.sent_at.is_some() {
278 MailState::Sent247 MailState::Sent
@@ -290,7 +259,6 @@ impl OutboxEntry {
290 }259 }
291 }260 }
292 261
293-/// Why a send failed. A transient failure is retried on the schedule; a permanent one gives up now.
294 #[derive(Debug, Clone, PartialEq, Eq)]262 #[derive(Debug, Clone, PartialEq, Eq)]
295 pub enum MailError {263 pub enum MailError {
296 Transient(String),264 Transient(String),
@@ -305,7 +273,6 @@ impl fmt::Display for MailError {
305 }273 }
306 }274 }
307 275
308-/// Checks the SMTP settings before they are stored. `enabled` needs a host and a sender.
309 pub fn validate_settings(update: &MailSettingsUpdate<'_>) -> crate::Result<()> {276 pub fn validate_settings(update: &MailSettingsUpdate<'_>) -> crate::Result<()> {
310 use crate::Error;277 use crate::Error;
311 let bad = |m: &str| Err(Error::Invalid(m.to_owned()));278 let bad = |m: &str| Err(Error::Invalid(m.to_owned()));
crates/forge-core/src/merge_queue.rsmodified+0 -14
@@ -1,11 +1,6 @@
1-//! The merge queue: pull requests waiting to be merged into a protected branch that requires the
2-//! queue. Each entry is `queued`, then `testing` (its candidate commit runs CI), then `merging`
3-//! (the target moves to the tested commit). An entry finishes as `failed` or `removed`.
4-
5 use crate::error::{Error, Result};1 use crate::error::{Error, Result};
6 use crate::pulls::MergeStyle;2 use crate::pulls::MergeStyle;
7 3
8-/// Where an entry is in the queue.
9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]4 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10 pub enum QueueState {5 pub enum QueueState {
11 Queued,6 Queued,
@@ -46,7 +41,6 @@ impl std::str::FromStr for QueueState {
46 }41 }
47 }42 }
48 43
49-/// One pull request in the queue.
50 #[derive(Debug, Clone, PartialEq, Eq)]44 #[derive(Debug, Clone, PartialEq, Eq)]
51 pub struct QueueEntry {45 pub struct QueueEntry {
52 pub id: String,46 pub id: String,
@@ -56,26 +50,18 @@ pub struct QueueEntry {
56 pub pull_number: i64,50 pub pull_number: i64,
57 pub merge_style: MergeStyle,51 pub merge_style: MergeStyle,
58 pub state: QueueState,52 pub state: QueueState,
59- /// Enqueue order within the branch. Smaller entries go first.
60 pub seq: i64,53 pub seq: i64,
61 pub enqueued_by: String,54 pub enqueued_by: String,
62 pub enqueued_at: String,55 pub enqueued_at: String,
63 pub updated_at: String,56 pub updated_at: String,
64 pub finished_at: Option<String>,57 pub finished_at: Option<String>,
65- /// Why a finished entry ended: `merged`, `removed`, `closed`, `head_changed`, `conflict` or
66- /// `tests_failed`.
67 pub reason: Option<String>,58 pub reason: Option<String>,
68- /// The target tip the candidate was built on.
69 pub base_oid: Option<String>,59 pub base_oid: Option<String>,
70- /// The candidate commit under test.
71 pub tested_oid: Option<String>,60 pub tested_oid: Option<String>,
72- /// The temporary ref that names the candidate.
73 pub test_ref: Option<String>,61 pub test_ref: Option<String>,
74- /// The CI run that tests the candidate.
75 pub run_id: Option<String>,62 pub run_id: Option<String>,
76 }63 }
77 64
78-/// The temporary ref that names a candidate of `branch` for pull request `number`.
79 pub fn test_ref_name(branch: &str, number: i64) -> String {65 pub fn test_ref_name(branch: &str, number: i64) -> String {
80 format!("refs/forge/merge-queue/{branch}/{number}")66 format!("refs/forge/merge-queue/{branch}/{number}")
81 }67 }
crates/forge-core/src/mirrors.rsmodified+0 -18
@@ -1,17 +1,8 @@
1-//! Push and pull mirrors: the direction enum and the mirror shape. The stored shape is in
2-//! migrations/0017_mirrors.sql; the store functions live in store/mirrors.rs.
3-//!
4-//! A mirror never carries its secret. `has_secret` says whether one is stored; the plaintext is
5-//! read back only through `Store::mirror_secret`, for the sync worker.
6-
7 use crate::model::Id;1 use crate::model::Id;
8 2
9-/// Which way refs flow. Stored as the `as_str` name.
10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]3 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11 pub enum MirrorDirection {4 pub enum MirrorDirection {
12- /// The repo's refs come from the remote URL.
13 Pull,5 Pull,
14- /// Our refs are pushed to the remote URL.
15 Push,6 Push,
16 }7 }
17 8
@@ -38,7 +29,6 @@ impl std::str::FromStr for MirrorDirection {
38 }29 }
39 }30 }
40 31
41-/// A repo mirror. Has no secret field; see `Store::mirror_secret`.
42 #[derive(Debug, Clone, PartialEq, Eq)]32 #[derive(Debug, Clone, PartialEq, Eq)]
43 pub struct Mirror {33 pub struct Mirror {
44 pub id: Id,34 pub id: Id,
@@ -56,7 +46,6 @@ pub struct Mirror {
56 pub created_at: String,46 pub created_at: String,
57 }47 }
58 48
59-/// Input for `Store::create_mirror`. `secret` is plaintext; the store seals it.
60 #[derive(Debug, Clone, Copy)]49 #[derive(Debug, Clone, Copy)]
61 pub struct NewMirror<'a> {50 pub struct NewMirror<'a> {
62 pub repo_id: &'a str,51 pub repo_id: &'a str,
@@ -67,20 +56,13 @@ pub struct NewMirror<'a> {
67 pub interval_minutes: u32,56 pub interval_minutes: u32,
68 }57 }
69 58
70-/// What `Store::update_mirror` does with the stored secret.
71 #[derive(Debug, Clone, Copy, PartialEq, Eq)]59 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
72 pub enum SecretUpdate<'a> {60 pub enum SecretUpdate<'a> {
73- /// Leave the stored secret as it is.
74 Keep,61 Keep,
75- /// Remove the stored secret.
76 Clear,62 Clear,
77- /// Replace the stored secret with this plaintext, which the store seals.
78 Set(&'a [u8]),63 Set(&'a [u8]),
79 }64 }
80 65
81-/// Most push mirrors one repo may have.
82 pub const MAX_PUSH_MIRRORS: u32 = 10;66 pub const MAX_PUSH_MIRRORS: u32 = 10;
83-/// Shortest allowed sync interval, in minutes. `0` means manual only.
84 pub const MIN_INTERVAL_MINUTES: u32 = 10;67 pub const MIN_INTERVAL_MINUTES: u32 = 10;
85-/// Default sync interval, in minutes.
86 pub const DEFAULT_INTERVAL_MINUTES: u32 = 480;68 pub const DEFAULT_INTERVAL_MINUTES: u32 = 480;
crates/forge-core/src/model.rsmodified+0 -24
@@ -1,5 +1,3 @@
1-//! Domain types. Stored shapes are described in docs/architecture.md, section 4.
2-
3 pub type Id = String;1 pub type Id = String;
4 2
5 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]3 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -21,7 +19,6 @@ pub enum Role {
21 Admin,19 Admin,
22 }20 }
23 21
24-/// What a `users` row stands for. An org is a row with `Org`; it can never authenticate.
25 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]22 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
26 #[serde(rename_all = "lowercase")]23 #[serde(rename_all = "lowercase")]
27 pub enum AccountKind {24 pub enum AccountKind {
@@ -37,37 +34,22 @@ pub struct User {
37 pub password_hash: String,34 pub password_hash: String,
38 pub is_admin: bool,35 pub is_admin: bool,
39 pub created_at: String,36 pub created_at: String,
40- /// Raw markdown, at most 2000 chars.
41 pub about: String,37 pub about: String,
42- /// Optional heading shown on the profile instead of the username. `None` when unset.
43 pub display_name: Option<String>,38 pub display_name: Option<String>,
44- /// IANA name, e.g. "Europe/Istanbul"; "UTC" by default.
45 pub timezone: String,39 pub timezone: String,
46- /// Hash of the current avatar, or `None` when the user has none. Filled by the user queries.
47 pub avatar_hash: Option<String>,40 pub avatar_hash: Option<String>,
48- /// Colour theme: "auto", "light" or "dark". Follows the browser when "auto".
49 pub theme: String,41 pub theme: String,
50- /// Language code, e.g. "en"; "auto" uses the instance default.
51 pub language: String,42 pub language: String,
52- /// Accent colour for the light theme: the id of a palette in forge-web's `accent_palette.rs`.
53- /// "sage" is the default.
54 pub accent: String,43 pub accent: String,
55- /// Accent colour for the dark theme, chosen separately from `accent`. "sage" is the default.
56 pub accent_dark: String,44 pub accent_dark: String,
57- /// Base (neutral background, surface and text) set for the light theme. "ink" is the default.
58 pub base_light: String,45 pub base_light: String,
59- /// Base set for the dark theme. "ink" is the default.
60 pub base_dark: String,46 pub base_dark: String,
61- /// Which side the main shell sidebar sits on: "left" (the default) or "right".
62 pub sidebar_side: String,47 pub sidebar_side: String,
63- /// `User` for a person, `Org` for an organization.
64 pub kind: AccountKind,48 pub kind: AccountKind,
65- /// Whether notifications are also sent by email (needs a verified email and instance mail).
66 pub email_notifications: bool,49 pub email_notifications: bool,
67 }50 }
68 51
69 impl User {52 impl User {
70- /// True for an organization row. Orgs never authenticate and never act as a person.
71 pub fn is_org(&self) -> bool {53 pub fn is_org(&self) -> bool {
72 self.kind == AccountKind::Org54 self.kind == AccountKind::Org
73 }55 }
@@ -84,8 +66,6 @@ pub struct Repo {
84 pub default_branch: String,66 pub default_branch: String,
85 pub archived: bool,67 pub archived: bool,
86 pub created_at: String,68 pub created_at: String,
87- /// The repo this one was forked from. `None` for originals and for forks whose parent was
88- /// deleted.
89 pub fork_of: Option<Id>,69 pub fork_of: Option<Id>,
90 }70 }
91 71
@@ -95,7 +75,6 @@ pub struct SshKey {
95 pub user_id: Id,75 pub user_id: Id,
96 pub title: String,76 pub title: String,
97 pub algorithm: String,77 pub algorithm: String,
98- /// Raw SSH wire-format public key blob (the bytes base64-encoded in authorized_keys).
99 pub key_blob: Vec<u8>,78 pub key_blob: Vec<u8>,
100 pub fingerprint: String,79 pub fingerprint: String,
101 pub created_at: String,80 pub created_at: String,
@@ -122,9 +101,7 @@ pub struct Session {
122 pub expires_at: String,101 pub expires_at: String,
123 pub last_seen: String,102 pub last_seen: String,
124 pub user_agent: Option<String>,103 pub user_agent: Option<String>,
125- /// The address the session signed in from.
126 pub ip: Option<String>,104 pub ip: Option<String>,
127- /// The address of the most recent request.
128 pub last_ip: Option<String>,105 pub last_ip: Option<String>,
129 }106 }
130 107
@@ -267,7 +244,6 @@ mod tests {
267 244
268 #[test]245 #[test]
269 fn visibility_and_role_round_trip_and_keep_stored_literals() {246 fn visibility_and_role_round_trip_and_keep_stored_literals() {
270- // Both are stored in the database, so the literals are pinned here.
271 let visibility = [247 let visibility = [
272 (Visibility::Public, "public"),248 (Visibility::Public, "public"),
273 (Visibility::Private, "private"),249 (Visibility::Private, "private"),
crates/forge-core/src/names.rsmodified+0 -18
@@ -1,10 +1,7 @@
1-//! Owner and repo name rules.
2-
3 use unicode_normalization::UnicodeNormalization;1 use unicode_normalization::UnicodeNormalization;
4 2
5 use crate::error::{Error, Result};3 use crate::error::{Error, Result};
6 4
7-/// Names that may not be used as owners or repos (they collide with routes).
8 pub const RESERVED: &[&str] = &[5 pub const RESERVED: &[&str] = &[
9 "api",6 "api",
10 "v2",7 "v2",
@@ -39,21 +36,16 @@ pub const RESERVED: &[&str] = &[
39 "issues",36 "issues",
40 "pulls",37 "pulls",
41 "snippets",38 "snippets",
42- // The reserved account that authored content is reassigned to on deletion.
43 "ghost",39 "ghost",
44 "favicon.ico",40 "favicon.ico",
45 "robots.txt",41 "robots.txt",
46 "security.txt",42 "security.txt",
47 ];43 ];
48 44
49-/// NFKC normalization plus case fold.
50 pub fn normalize_name(input: &str) -> String {45 pub fn normalize_name(input: &str) -> String {
51 input.nfkc().collect::<String>().to_lowercase()46 input.nfkc().collect::<String>().to_lowercase()
52 }47 }
53 48
54-/// Returns the folded name, or `Error::InvalidName`.
55-/// Allowed characters `[a-z0-9._-]`; must not start with `-` or `.`; must not end in `.git` or `.atom`.
56-/// Repo names must also not end in `.wiki`, so that `<name>.wiki.git` names the wiki unambiguously.
57 pub fn validate_name(input: &str) -> Result<String> {49 pub fn validate_name(input: &str) -> Result<String> {
58 let name = normalize_name(input);50 let name = normalize_name(input);
59 if !name51 if !name
@@ -72,17 +64,11 @@ pub fn validate_name(input: &str) -> Result<String> {
72 Ok(name)64 Ok(name)
73 }65 }
74 66
75-/// The repo name a wiki transport path names: `name.wiki` or `name.wiki.git` gives `name`. `None`
76-/// for any other name. Repo names never end in `.wiki`, so the mapping is unambiguous.
77 pub fn wiki_base(path_name: &str) -> Option<&str> {67 pub fn wiki_base(path_name: &str) -> Option<&str> {
78 let base = path_name.strip_suffix(".git").unwrap_or(path_name);68 let base = path_name.strip_suffix(".git").unwrap_or(path_name);
79 base.strip_suffix(".wiki").filter(|b| !b.is_empty())69 base.strip_suffix(".wiki").filter(|b| !b.is_empty())
80 }70 }
81 71
82-/// Validates an owner (user) name. Returns `(display, folded)`: the NFKC-normalized input with
83-/// its case kept, and the lowercase form used for uniqueness and lookup.
84-/// Display characters are `[A-Za-z0-9._-]`; the folded form must pass the same rules as
85-/// `validate_name`.
86 pub fn validate_username(input: &str) -> Result<(String, String)> {72 pub fn validate_username(input: &str) -> Result<(String, String)> {
87 let display: String = input.nfkc().collect();73 let display: String = input.nfkc().collect();
88 if !display74 if !display
@@ -99,11 +85,8 @@ pub fn validate_username(input: &str) -> Result<(String, String)> {
99 Ok((display, folded))85 Ok((display, folded))
100 }86 }
101 87
102-/// Message for a username change that alters more than capitalization.
103 pub const CAPITALIZATION_ONLY: &str = "Only the capitalization can be changed.";88 pub const CAPITALIZATION_ONLY: &str = "Only the capitalization can be changed.";
104 89
105-/// Validates `new_display` and checks that it only changes the casing of `current`.
106-/// Returns the display form to store.
107 pub fn capitalization_change(current: &str, new_display: &str) -> Result<String> {90 pub fn capitalization_change(current: &str, new_display: &str) -> Result<String> {
108 let (display, folded) = validate_username(new_display)?;91 let (display, folded) = validate_username(new_display)?;
109 if folded != normalize_name(current) {92 if folded != normalize_name(current) {
@@ -116,7 +99,6 @@ fn invalid(input: &str, why: &str) -> Error {
116 Error::InvalidName(format!("{input:?}: {why}"))99 Error::InvalidName(format!("{input:?}: {why}"))
117 }100 }
118 101
119-/// Length, leading/trailing, `..`, and reserved-name rules, applied to a folded name.
120 fn check_folded(input: &str, name: &str) -> Result<()> {102 fn check_folded(input: &str, name: &str) -> Result<()> {
121 if !(1..=64).contains(&name.chars().count()) {103 if !(1..=64).contains(&name.chars().count()) {
122 return Err(invalid(input, "length must be 1 to 64 characters"));104 return Err(invalid(input, "length must be 1 to 64 characters"));
crates/forge-core/src/notifications.rsmodified+0 -14
@@ -1,16 +1,10 @@
1-//! Notification models: repo watch levels, issue subscriptions and inbox entries.
2-
3 use crate::issues::IssueState;1 use crate::issues::IssueState;
4 use crate::model::Id;2 use crate::model::Id;
5 3
6-/// How much activity a user hears about in a repo. A user with no row is `Participating`.
7 #[derive(Debug, Clone, Copy, PartialEq, Eq)]4 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
8 pub enum WatchLevel {5 pub enum WatchLevel {
9- /// All activity in the repo.
10 Watching,6 Watching,
11- /// Only the issues and pulls the user is subscribed to, and mentions.
12 Participating,7 Participating,
13- /// Nothing from the repo, even subscribed threads. Mentions still notify.
14 Ignoring,8 Ignoring,
15 }9 }
16 10
@@ -33,11 +27,9 @@ impl WatchLevel {
33 }27 }
34 }28 }
35 29
36-/// State of an issue subscription row.
37 #[derive(Debug, Clone, Copy, PartialEq, Eq)]30 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38 pub enum SubState {31 pub enum SubState {
39 Subscribed,32 Subscribed,
40- /// Explicit opt-out. Auto-subscribe never replaces it.
41 Ignored,33 Ignored,
42 }34 }
43 35
@@ -58,7 +50,6 @@ impl SubState {
58 }50 }
59 }51 }
60 52
61-/// Why a user is notified. The stronger reason wins while a thread is unread.
62 #[derive(Debug, Clone, Copy, PartialEq, Eq)]53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
63 pub enum Reason {54 pub enum Reason {
64 Mention,55 Mention,
@@ -99,8 +90,6 @@ impl Reason {
99 }90 }
100 }91 }
101 92
102- /// Strength, higher is stronger: mention > assign > review_requested > author > comment >
103- /// state_change > subscribed > watching.
104 pub fn rank(self) -> u8 {93 pub fn rank(self) -> u8 {
105 match self {94 match self {
106 Reason::Mention => 8,95 Reason::Mention => 8,
@@ -115,7 +104,6 @@ impl Reason {
115 }104 }
116 }105 }
117 106
118-/// One inbox row joined with its repo, issue or pull, and the last actor.
119 #[derive(Debug, Clone, PartialEq, Eq)]107 #[derive(Debug, Clone, PartialEq, Eq)]
120 pub struct Notification {108 pub struct Notification {
121 pub id: Id,109 pub id: Id,
@@ -124,13 +112,11 @@ pub struct Notification {
124 pub repo_name: String,112 pub repo_name: String,
125 pub issue_id: Id,113 pub issue_id: Id,
126 pub number: i64,114 pub number: i64,
127- /// True for pull requests (`issues.kind = 'pull'`).
128 pub is_pull: bool,115 pub is_pull: bool,
129 pub title: String,116 pub title: String,
130 pub issue_state: IssueState,117 pub issue_state: IssueState,
131 pub reason: Reason,118 pub reason: Reason,
132 pub last_activity: String,119 pub last_activity: String,
133- /// `None` when the actor was deleted without a ghost reassignment or the activity had none.
134 pub last_actor_name: Option<String>,120 pub last_actor_name: Option<String>,
135 pub unread: bool,121 pub unread: bool,
136 pub updated_at: String,122 pub updated_at: String,
crates/forge-core/src/oci.rsmodified+0 -29
@@ -1,10 +1,3 @@
1-//! Container registry rules shared by the web layer: repository names, digests, tags, the
2-//! manifest media types, the reference scan of a manifest, and the short-lived bearer token that
3-//! `docker login` and `podman` exchange for their credentials.
4-//!
5-//! Token format: `base64url("oci1|<user id or empty>|<expires>") + "." + base64url(hmac)`. The
6-//! MAC covers the payload under its own domain tag, so an LFS token never verifies here.
7-
8 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};1 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
9 use hmac::{Hmac, KeyInit, Mac};2 use hmac::{Hmac, KeyInit, Mac};
10 use serde_json::Value;3 use serde_json::Value;
@@ -13,7 +6,6 @@ use subtle::ConstantTimeEq;
13 6
14 type HmacSha256 = Hmac<Sha256>;7 type HmacSha256 = Hmac<Sha256>;
15 8
16-/// The media types a manifest may be pushed as.
17 pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [9 pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [
18 "application/vnd.oci.image.manifest.v1+json",10 "application/vnd.oci.image.manifest.v1+json",
19 "application/vnd.oci.image.index.v1+json",11 "application/vnd.oci.image.index.v1+json",
@@ -21,18 +13,13 @@ pub const MANIFEST_MEDIA_TYPES: [&str; 4] = [
21 "application/vnd.docker.distribution.manifest.list.v2+json",13 "application/vnd.docker.distribution.manifest.list.v2+json",
22 ];14 ];
23 15
24-/// Longest repository name the spec allows.
25 const MAX_REPO_NAME: usize = 255;16 const MAX_REPO_NAME: usize = 255;
26-/// Longest tag the spec allows.
27 const MAX_TAG: usize = 128;17 const MAX_TAG: usize = 128;
28 18
29-/// True for one of [`MANIFEST_MEDIA_TYPES`].
30 pub fn is_manifest_media_type(media_type: &str) -> bool {19 pub fn is_manifest_media_type(media_type: &str) -> bool {
31 MANIFEST_MEDIA_TYPES.contains(&media_type)20 MANIFEST_MEDIA_TYPES.contains(&media_type)
32 }21 }
33 22
34-/// True for one path segment of a repository name: lowercase letters and digits, joined by a
35-/// single `.` or `_`, or by runs of `-`, and starting and ending with a letter or digit.
36 fn valid_segment(segment: &str) -> bool {23 fn valid_segment(segment: &str) -> bool {
37 let bytes = segment.as_bytes();24 let bytes = segment.as_bytes();
38 if bytes.is_empty() {25 if bytes.is_empty() {
@@ -58,8 +45,6 @@ fn valid_segment(segment: &str) -> bool {
58 true45 true
59 }46 }
60 47
61-/// The owner and the image path of a repository name such as `tahinli/app` or `tahinli/a/b`.
62-/// `None` when the name has no owner segment or no image segment, or a segment is malformed.
63 pub fn split_repo_name(name: &str) -> Option<(&str, &str)> {48 pub fn split_repo_name(name: &str) -> Option<(&str, &str)> {
64 if name.len() > MAX_REPO_NAME {49 if name.len() > MAX_REPO_NAME {
65 return None;50 return None;
@@ -71,8 +56,6 @@ pub fn split_repo_name(name: &str) -> Option<(&str, &str)> {
71 Some((owner, image))56 Some((owner, image))
72 }57 }
73 58
74-/// The lowercase `sha256:<hex>` digest, returned as its 64 hex characters. `None` for any other
75-/// algorithm or a malformed value.
76 pub fn parse_digest(digest: &str) -> Option<&str> {59 pub fn parse_digest(digest: &str) -> Option<&str> {
77 let hex = digest.strip_prefix("sha256:")?;60 let hex = digest.strip_prefix("sha256:")?;
78 let valid = hex.len() == 6461 let valid = hex.len() == 64
@@ -82,7 +65,6 @@ pub fn parse_digest(digest: &str) -> Option<&str> {
82 valid.then_some(hex)65 valid.then_some(hex)
83 }66 }
84 67
85-/// True for a tag: up to 128 characters from `[A-Za-z0-9_.-]`, not starting with `.` or `-`.
86 pub fn valid_tag(tag: &str) -> bool {68 pub fn valid_tag(tag: &str) -> bool {
87 let bytes = tag.as_bytes();69 let bytes = tag.as_bytes();
88 !bytes.is_empty()70 !bytes.is_empty()
@@ -93,19 +75,13 @@ pub fn valid_tag(tag: &str) -> bool {
93 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))75 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
94 }76 }
95 77
96-/// What a manifest refers to.
97 #[derive(Debug, Clone, PartialEq, Eq)]78 #[derive(Debug, Clone, PartialEq, Eq)]
98 pub struct ManifestRefs {79 pub struct ManifestRefs {
99- /// `sha256:<hex>` digests of the config and layers, or of the child manifests of an index.
100 pub digests: Vec<String>,80 pub digests: Vec<String>,
101- /// Bytes of the image: its config and layers. For an index, the manifest's own length.
102 pub total_size: u64,81 pub total_size: u64,
103- /// True for an index or manifest list, whose digests name manifests rather than blobs.
104 pub is_index: bool,82 pub is_index: bool,
105 }83 }
106 84
107-/// Reads the digests a manifest names. A manifest with a `manifests` array is an index. Any other
108-/// manifest must name a `config` and may name layers. Every digest must be `sha256:<hex>`.
109 pub fn scan_manifest(bytes: &[u8]) -> Result<ManifestRefs, String> {85 pub fn scan_manifest(bytes: &[u8]) -> Result<ManifestRefs, String> {
110 let value: Value =86 let value: Value =
111 serde_json::from_slice(bytes).map_err(|e| format!("manifest is not JSON: {e}"))?;87 serde_json::from_slice(bytes).map_err(|e| format!("manifest is not JSON: {e}"))?;
@@ -159,7 +135,6 @@ fn descriptor_size(descriptor: &Value) -> u64 {
159 }135 }
160 136
161 fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 {137 fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 {
162- // HMAC accepts keys of any length, so construction with a 32-byte key cannot fail.
163 let mut mac =138 let mut mac =
164 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");139 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");
165 mac.update(b"oci\0");140 mac.update(b"oci\0");
@@ -167,8 +142,6 @@ fn mac_for(key: &[u8; 32], payload: &[u8]) -> HmacSha256 {
167 mac142 mac
168 }143 }
169 144
170-/// Issues a bearer token for `subject` (a user id, or `None` for anonymous), valid until
171-/// `expires_unix` seconds since the epoch.
172 pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String {145 pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) -> String {
173 let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or(""));146 let payload = format!("oci1|{}|{expires_unix}", subject.unwrap_or(""));
174 let tag = mac_for(key, payload.as_bytes()).finalize().into_bytes();147 let tag = mac_for(key, payload.as_bytes()).finalize().into_bytes();
@@ -179,8 +152,6 @@ pub fn issue_token(key: &[u8; 32], subject: Option<&str>, expires_unix: i64) ->
179 )152 )
180 }153 }
181 154
182-/// Checks a bearer token at `now_unix`. Returns the subject it names (`None` for anonymous), or
183-/// `None` when the token is malformed, forged, or expired.
184 pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option<Option<String>> {155 pub fn verify_token(key: &[u8; 32], token: &str, now_unix: i64) -> Option<Option<String>> {
185 let (payload_b64, mac_b64) = token.split_once('.')?;156 let (payload_b64, mac_b64) = token.split_once('.')?;
186 let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?;157 let payload = BASE64_URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
crates/forge-core/src/packages.rsmodified+0 -18
@@ -1,16 +1,6 @@
1-//! Package registries. An owner (user or org) holds packages of one `kind`; each package has
2-//! versions. The stored shape is in migrations/0061_packages.sql, the store functions in
3-//! store/packages.rs. Bytes of a `.crate` live in blob storage under `packages/<version id>`;
4-//! only metadata is stored here. Kinds are `cargo` and `oci` (container images).
5-
6-/// The Cargo registry kind.
7 pub const KIND_CARGO: &str = "cargo";1 pub const KIND_CARGO: &str = "cargo";
8-/// The container registry kind. Its packages are images; their tags and manifests are in the
9-/// `oci_*` tables (migrations/0062_oci.sql), not in `package_versions`.
10 pub const KIND_OCI: &str = "oci";2 pub const KIND_OCI: &str = "oci";
11 3
12-/// A package. `name_key` is the lowercase name the index uses; `private` hides the package and
13-/// its index from everyone but the owner's members.
14 #[derive(Debug, Clone, PartialEq, Eq)]4 #[derive(Debug, Clone, PartialEq, Eq)]
15 pub struct Package {5 pub struct Package {
16 pub id: String,6 pub id: String,
@@ -24,17 +14,14 @@ pub struct Package {
24 pub updated_at: String,14 pub updated_at: String,
25 }15 }
26 16
27-/// One published version of a package.
28 #[derive(Debug, Clone, PartialEq, Eq)]17 #[derive(Debug, Clone, PartialEq, Eq)]
29 pub struct PackageVersion {18 pub struct PackageVersion {
30 pub id: String,19 pub id: String,
31 pub package_id: String,20 pub package_id: String,
32 pub version: String,21 pub version: String,
33 pub yanked: bool,22 pub yanked: bool,
34- /// Lowercase hex sha256 of the `.crate` file.
35 pub checksum: String,23 pub checksum: String,
36 pub size: u64,24 pub size: u64,
37- /// The index line as published, with `yanked` false. Served with the current yank state.
38 pub index_json: String,25 pub index_json: String,
39 pub description: Option<String>,26 pub description: Option<String>,
40 pub readme: Option<String>,27 pub readme: Option<String>,
@@ -42,7 +29,6 @@ pub struct PackageVersion {
42 pub created_at: String,29 pub created_at: String,
43 }30 }
44 31
45-/// A package with what its list shows: how many versions it has and the newest one.
46 #[derive(Debug, Clone, PartialEq, Eq)]32 #[derive(Debug, Clone, PartialEq, Eq)]
47 pub struct PackageSummary {33 pub struct PackageSummary {
48 pub package: Package,34 pub package: Package,
@@ -51,7 +37,6 @@ pub struct PackageSummary {
51 pub latest_description: Option<String>,37 pub latest_description: Option<String>,
52 }38 }
53 39
54-/// Input for `Store::publish_package_version`.
55 #[derive(Debug, Clone, Copy)]40 #[derive(Debug, Clone, Copy)]
56 pub struct NewPackageVersion<'a> {41 pub struct NewPackageVersion<'a> {
57 pub package_id: &'a str,42 pub package_id: &'a str,
@@ -64,7 +49,6 @@ pub struct NewPackageVersion<'a> {
64 pub publisher_id: &'a str,49 pub publisher_id: &'a str,
65 }50 }
66 51
67-/// A container manifest as pushed. `content` is the exact JSON, so its digest still checks.
68 #[derive(Debug, Clone, PartialEq, Eq)]52 #[derive(Debug, Clone, PartialEq, Eq)]
69 pub struct OciManifest {53 pub struct OciManifest {
70 pub id: String,54 pub id: String,
@@ -72,12 +56,10 @@ pub struct OciManifest {
72 pub digest: String,56 pub digest: String,
73 pub media_type: String,57 pub media_type: String,
74 pub content: String,58 pub content: String,
75- /// The image's config and layers in bytes, or the manifest's length for an index.
76 pub size: u64,59 pub size: u64,
77 pub created_at: String,60 pub created_at: String,
78 }61 }
79 62
80-/// One tag of a container image, with the manifest it points at.
81 #[derive(Debug, Clone, PartialEq, Eq)]63 #[derive(Debug, Clone, PartialEq, Eq)]
82 pub struct OciTag {64 pub struct OciTag {
83 pub tag: String,65 pub tag: String,
crates/forge-core/src/password.rsmodified+0 -5
@@ -1,21 +1,16 @@
1-//! Password hashing with argon2id.
2-
3 use argon2::Argon2;1 use argon2::Argon2;
4 use argon2::password_hash::phc::PasswordHash;2 use argon2::password_hash::phc::PasswordHash;
5 use argon2::password_hash::{PasswordHasher, PasswordVerifier};3 use argon2::password_hash::{PasswordHasher, PasswordVerifier};
6 4
7 use crate::error::{Error, Result};5 use crate::error::{Error, Result};
8 6
9-/// Hashes `pw` with argon2id (default parameters) and a random salt. Returns a PHC string.
10 pub fn hash_password(pw: &str) -> Result<String> {7 pub fn hash_password(pw: &str) -> Result<String> {
11- // The trait method draws a fresh salt from the OS RNG.
12 Argon2::default()8 Argon2::default()
13 .hash_password(pw.as_bytes())9 .hash_password(pw.as_bytes())
14 .map(|h| h.to_string())10 .map(|h| h.to_string())
15 .map_err(|e| Error::Crypto(format!("argon2: {e}")))11 .map_err(|e| Error::Crypto(format!("argon2: {e}")))
16 }12 }
17 13
18-/// Returns true only if `pw` matches the PHC string `hash`. Any error yields false.
19 pub fn verify_password(pw: &str, hash: &str) -> bool {14 pub fn verify_password(pw: &str, hash: &str) -> bool {
20 let Ok(parsed) = PasswordHash::new(hash) else {15 let Ok(parsed) = PasswordHash::new(hash) else {
21 return false;16 return false;
crates/forge-core/src/protection.rsmodified+0 -37
@@ -1,10 +1,6 @@
1-//! Branch protection rules: pattern syntax, validation, matching and effective-rule resolution.
2-
3 use crate::error::{Error, Result};1 use crate::error::{Error, Result};
4 2
5-/// Longest accepted pattern, in bytes.
6 pub const MAX_PATTERN_BYTES: usize = 200;3 pub const MAX_PATTERN_BYTES: usize = 200;
7-/// Largest accepted `required_approvals`.
8 pub const MAX_REQUIRED_APPROVALS: u32 = 20;4 pub const MAX_REQUIRED_APPROVALS: u32 = 20;
9 5
10 #[derive(Debug, Clone, PartialEq)]6 #[derive(Debug, Clone, PartialEq)]
@@ -14,20 +10,11 @@ pub struct BranchRule {
14 pub pattern: String,10 pub pattern: String,
15 pub allow_force_push: bool,11 pub allow_force_push: bool,
16 pub allow_deletion: bool,12 pub allow_deletion: bool,
17- /// Approvals from Write-or-higher reviewers that a pull request needs before it can merge.
18 pub required_approvals: u32,13 pub required_approvals: u32,
19- /// A changes-requested review from a Write-or-higher reviewer blocks the merge.
20 pub block_on_changes_requested: bool,14 pub block_on_changes_requested: bool,
21- /// The pull request head must contain the base tip before it can merge.
22 pub require_up_to_date: bool,15 pub require_up_to_date: bool,
23- /// Direct pushes to the branch are rejected for everyone but repo admins. Merges through
24- /// pull requests are unaffected.
25 pub restrict_push: bool,16 pub restrict_push: bool,
26- /// Merges go through the merge queue: the merge box queues the pull request, and the queue
27- /// moves the branch only to commits CI tested. Direct merges are refused.
28 pub require_merge_queue: bool,17 pub require_merge_queue: bool,
29- /// Commit status contexts (CI job names such as `ci/test`, or any reported context) that must
30- /// all be `success` on the pull request head before it can merge.
31 pub required_checks: Vec<String>,18 pub required_checks: Vec<String>,
32 pub created_at: String,19 pub created_at: String,
33 }20 }
@@ -47,7 +34,6 @@ impl BranchRule {
47 }34 }
48 }35 }
49 36
50-/// The settings a rule saves, without its identity. `Default` is the unprotected branch.
51 #[derive(Debug, Clone, Default, PartialEq, Eq)]37 #[derive(Debug, Clone, Default, PartialEq, Eq)]
52 pub struct RuleFlags {38 pub struct RuleFlags {
53 pub allow_force_push: bool,39 pub allow_force_push: bool,
@@ -61,7 +47,6 @@ pub struct RuleFlags {
61 }47 }
62 48
63 impl RuleFlags {49 impl RuleFlags {
64- /// Only the force-push and deletion flags set; the merge and push rules off.
65 pub fn basic(allow_force_push: bool, allow_deletion: bool) -> Self {50 pub fn basic(allow_force_push: bool, allow_deletion: bool) -> Self {
66 Self {51 Self {
67 allow_force_push,52 allow_force_push,
@@ -71,7 +56,6 @@ impl RuleFlags {
71 }56 }
72 }57 }
73 58
74-/// Rejects `required_approvals` above `MAX_REQUIRED_APPROVALS`.
75 pub fn validate_required_approvals(n: u32) -> Result<()> {59 pub fn validate_required_approvals(n: u32) -> Result<()> {
76 if n > MAX_REQUIRED_APPROVALS {60 if n > MAX_REQUIRED_APPROVALS {
77 return Err(Error::Invalid(format!(61 return Err(Error::Invalid(format!(
@@ -81,12 +65,9 @@ pub fn validate_required_approvals(n: u32) -> Result<()> {
81 Ok(())65 Ok(())
82 }66 }
83 67
84-/// Most required check contexts on one rule.
85 pub const MAX_REQUIRED_CHECKS: usize = 50;68 pub const MAX_REQUIRED_CHECKS: usize = 50;
86-/// Longest accepted check context, in bytes.
87 pub const MAX_CHECK_CONTEXT_BYTES: usize = 200;69 pub const MAX_CHECK_CONTEXT_BYTES: usize = 200;
88 70
89-/// Trims, drops blanks and duplicates (keeping first-seen order) and validates the contexts.
90 pub fn normalize_required_checks(raw: &[String]) -> Result<Vec<String>> {71 pub fn normalize_required_checks(raw: &[String]) -> Result<Vec<String>> {
91 let mut out: Vec<String> = Vec::new();72 let mut out: Vec<String> = Vec::new();
92 for item in raw {73 for item in raw {
@@ -109,9 +90,6 @@ pub fn normalize_required_checks(raw: &[String]) -> Result<Vec<String>> {
109 Ok(out)90 Ok(out)
110 }91 }
111 92
112-/// Pattern syntax: a literal branch name, `*` matches any run of chars except `/`, `**` matches anything
113-/// including `/`. Max 200 bytes, it must be a valid branch name otherwise (no `..`, no leading `-`, no
114-/// control or space chars, no `~^:?[\`). The pattern must not include the `refs/heads/` prefix.
115 pub fn validate_pattern(p: &str) -> Result<()> {93 pub fn validate_pattern(p: &str) -> Result<()> {
116 let invalid = |why: &str| Err(Error::Invalid(format!("branch pattern {why}")));94 let invalid = |why: &str| Err(Error::Invalid(format!("branch pattern {why}")));
117 if p.is_empty() {95 if p.is_empty() {
@@ -154,9 +132,7 @@ pub fn validate_pattern(p: &str) -> Result<()> {
154 #[derive(Clone, Copy, PartialEq, Eq)]132 #[derive(Clone, Copy, PartialEq, Eq)]
155 enum Tok {133 enum Tok {
156 Char(char),134 Char(char),
157- /// `*`: any run of chars except `/`.
158 Star,135 Star,
159- /// `**`: any run of chars, `/` included.
160 AnyStar,136 AnyStar,
161 }137 }
162 138
@@ -178,12 +154,9 @@ fn tokenize(pattern: &str) -> Vec<Tok> {
178 out154 out
179 }155 }
180 156
181-/// Whether `branch` matches `pattern`. Dynamic programming over (token, char) positions, so the
182-/// cost is bounded by pattern length times branch length.
183 pub fn pattern_matches(pattern: &str, branch: &str) -> bool {157 pub fn pattern_matches(pattern: &str, branch: &str) -> bool {
184 let chars: Vec<char> = branch.chars().collect();158 let chars: Vec<char> = branch.chars().collect();
185 let n = chars.len();159 let n = chars.len();
186- // reach[j]: the tokens consumed so far can match chars[..j].
187 let mut reach = vec![false; n + 1];160 let mut reach = vec![false; n + 1];
188 reach[0] = true;161 reach[0] = true;
189 for tok in tokenize(pattern) {162 for tok in tokenize(pattern) {
@@ -216,18 +189,11 @@ fn is_literal(pattern: &str) -> bool {
216 !pattern.contains('*')189 !pattern.contains('*')
217 }190 }
218 191
219-/// Rules for `branch` (short name, without refs/heads/):
220-/// 1. If any rule matches: the most specific one wins. A literal (no `*`) beats a glob; among globs the
221-/// longest pattern wins, and ties go to the earliest created_at.
222-/// 2. Otherwise, if `branch == default_branch`: built-in protection {force_push: false, deletion: false}.
223-/// 3. Otherwise: unprotected {force_push: true, deletion: true}.
224 pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> RuleFlags {192 pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> RuleFlags {
225 let best = rules193 let best = rules
226 .iter()194 .iter()
227 .filter(|r| pattern_matches(&r.pattern, branch))195 .filter(|r| pattern_matches(&r.pattern, branch))
228 .min_by(|a, b| {196 .min_by(|a, b| {
229- // Literal first, then longer pattern, then earliest creation, then pattern text
230- // so the result never depends on the order of `rules`.
231 is_literal(&b.pattern)197 is_literal(&b.pattern)
232 .cmp(&is_literal(&a.pattern))198 .cmp(&is_literal(&a.pattern))
233 .then_with(|| b.pattern.len().cmp(&a.pattern.len()))199 .then_with(|| b.pattern.len().cmp(&a.pattern.len()))
@@ -342,13 +308,11 @@ mod tests {
342 308
343 #[test]309 #[test]
344 fn effective_longer_glob_wins() {310 fn effective_longer_glob_wins() {
345- // Both `*` and `rel*` match `release`; the longer `rel*` wins even though `*` is older.
346 let rules = [rule("*", true, true, "0"), rule("rel*", false, false, "1")];311 let rules = [rule("*", true, true, "0"), rule("rel*", false, false, "1")];
347 assert_eq!(312 assert_eq!(
348 effective(&rules, "main", "release"),313 effective(&rules, "main", "release"),
349 RuleFlags::basic(false, false)314 RuleFlags::basic(false, false)
350 );315 );
351- // `release/**` is longer than `release/*`, so it wins for nested names.
352 let rules = [316 let rules = [
353 rule("release/*", true, true, "1"),317 rule("release/*", true, true, "1"),
354 rule("release/**", false, false, "2"),318 rule("release/**", false, false, "2"),
@@ -380,7 +344,6 @@ mod tests {
380 required_checks: Vec::new(),344 required_checks: Vec::new(),
381 }345 }
382 );346 );
383- // Unprotected and built-in default branches carry no merge rules.
384 assert_eq!(effective(&rules, "main", "feature").required_approvals, 0);347 assert_eq!(effective(&rules, "main", "feature").required_approvals, 0);
385 assert!(!effective(&[], "main", "main").restrict_push);348 assert!(!effective(&[], "main", "main").restrict_push);
386 }349 }
crates/forge-core/src/pulls.rsmodified+0 -15
@@ -1,12 +1,7 @@
1-//! Pull request types. A pull request is an issue with `kind = 'pull'` plus a `pull_requests`
2-//! row. The stored shape is in migrations/0007_pulls.sql; the store functions live in
3-//! store/pulls.rs.
4-
5 use crate::error::{Error, Result};1 use crate::error::{Error, Result};
6 use crate::issues::Issue;2 use crate::issues::Issue;
7 use crate::model::Id;3 use crate::model::Id;
8 4
9-/// Mergeability of a pull request, as last computed.
10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]5 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
11 pub enum Mergeable {6 pub enum Mergeable {
12 Unknown,7 Unknown,
@@ -45,15 +40,11 @@ impl std::str::FromStr for Mergeable {
45 40
46 #[derive(Debug, Clone, PartialEq)]41 #[derive(Debug, Clone, PartialEq)]
47 pub struct PullRequest {42 pub struct PullRequest {
48- /// The backing issue row (`kind = 'pull'`): number, title, state, author and so on.
49 pub issue: Issue,43 pub issue: Issue,
50 pub base_branch: String,44 pub base_branch: String,
51- /// `None` once the head repo has been deleted.
52 pub head_repo_id: Option<Id>,45 pub head_repo_id: Option<Id>,
53 pub head_branch: String,46 pub head_branch: String,
54- /// Last known head commit (also `refs/pull/N/head` in the base repo).
55 pub head_oid: String,47 pub head_oid: String,
56- /// Base branch tip when mergeability was last computed.
57 pub base_oid: String,48 pub base_oid: String,
58 pub merge_base: Option<String>,49 pub merge_base: Option<String>,
59 pub mergeable: Mergeable,50 pub mergeable: Mergeable,
@@ -61,20 +52,16 @@ pub struct PullRequest {
61 pub merged_at: Option<String>,52 pub merged_at: Option<String>,
62 pub merged_by: Option<Id>,53 pub merged_by: Option<Id>,
63 pub merge_commit: Option<String>,54 pub merge_commit: Option<String>,
64- /// A draft cannot be merged and does not notify reviewers until marked ready.
65 pub draft: bool,55 pub draft: bool,
66- /// Set while auto-merge is enabled.
67 pub auto_merge: Option<AutoMerge>,56 pub auto_merge: Option<AutoMerge>,
68 }57 }
69 58
70-/// Auto-merge settings: the merge runs as `user_id` with `style` once the merge gate passes.
71 #[derive(Debug, Clone, PartialEq, Eq)]59 #[derive(Debug, Clone, PartialEq, Eq)]
72 pub struct AutoMerge {60 pub struct AutoMerge {
73 pub style: MergeStyle,61 pub style: MergeStyle,
74 pub user_id: Id,62 pub user_id: Id,
75 }63 }
76 64
77-/// How a pull request is merged into its base branch.
78 #[derive(Debug, Clone, Copy, PartialEq, Eq)]65 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
79 pub enum MergeStyle {66 pub enum MergeStyle {
80 Merge,67 Merge,
@@ -84,7 +71,6 @@ pub enum MergeStyle {
84 }71 }
85 72
86 impl MergeStyle {73 impl MergeStyle {
87- /// The value used in forms and URLs.
88 pub fn as_str(&self) -> &'static str {74 pub fn as_str(&self) -> &'static str {
89 match self {75 match self {
90 MergeStyle::Merge => "merge",76 MergeStyle::Merge => "merge",
@@ -115,7 +101,6 @@ mod tests {
115 101
116 #[test]102 #[test]
117 fn mergeable_and_merge_style_round_trip_and_keep_stored_literals() {103 fn mergeable_and_merge_style_round_trip_and_keep_stored_literals() {
118- // Both are stored in the database, so the literals are pinned here.
119 let mergeable = [104 let mergeable = [
120 (Mergeable::Unknown, "unknown"),105 (Mergeable::Unknown, "unknown"),
121 (Mergeable::Clean, "clean"),106 (Mergeable::Clean, "clean"),
crates/forge-core/src/raw_token.rsmodified+0 -11
@@ -1,8 +1,3 @@
1-//! Signed tokens for private raw-file URLs.
2-//!
3-//! Token format: `"<expires>.<base64url-nopad(hmac_sha256)>"`, where the MAC covers
4-//! `"raw-v1:" + repo_id + ":" + expires`.
5-
6 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};1 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
7 use hmac::{Hmac, KeyInit, Mac};2 use hmac::{Hmac, KeyInit, Mac};
8 use sha2::Sha256;3 use sha2::Sha256;
@@ -12,7 +7,6 @@ type HmacSha256 = Hmac<Sha256>;
12 const MAC_LEN: usize = 32;7 const MAC_LEN: usize = 32;
13 8
14 fn mac_for(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> HmacSha256 {9 fn mac_for(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> HmacSha256 {
15- // HMAC accepts keys of any length, so construction with a 32-byte key cannot fail.
16 let mut mac =10 let mut mac =
17 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");11 <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length");
18 mac.update(b"raw-v1:");12 mac.update(b"raw-v1:");
@@ -22,19 +16,15 @@ fn mac_for(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> HmacSha256 {
22 mac16 mac
23 }17 }
24 18
25-/// Signs access to `repo_id`'s raw files until `expires_unix` (seconds since the epoch).
26 pub fn sign_raw(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> String {19 pub fn sign_raw(key: &[u8; 32], repo_id: &str, expires_unix: i64) -> String {
27 let tag = mac_for(key, repo_id, expires_unix).finalize().into_bytes();20 let tag = mac_for(key, repo_id, expires_unix).finalize().into_bytes();
28 format!("{expires_unix}.{}", BASE64_URL_SAFE_NO_PAD.encode(tag))21 format!("{expires_unix}.{}", BASE64_URL_SAFE_NO_PAD.encode(tag))
29 }22 }
30 23
31-/// Verifies a token for `repo_id` at time `now_unix`. Rejects malformed input, expired
32-/// tokens (`now >= expires`) and bad MACs. The MAC comparison is constant time.
33 pub fn verify_raw(key: &[u8; 32], token: &str, repo_id: &str, now_unix: i64) -> bool {24 pub fn verify_raw(key: &[u8; 32], token: &str, repo_id: &str, now_unix: i64) -> bool {
34 let Some((expires_str, mac_str)) = token.split_once('.') else {25 let Some((expires_str, mac_str)) = token.split_once('.') else {
35 return false;26 return false;
36 };27 };
37- // Strict canonical decimal: no sign, no leading zeros, no whitespace.
38 let Ok(expires) = expires_str.parse::<i64>() else {28 let Ok(expires) = expires_str.parse::<i64>() else {
39 return false;29 return false;
40 };30 };
@@ -78,7 +68,6 @@ mod tests {
78 #[test]68 #[test]
79 fn expired_is_rejected() {69 fn expired_is_rejected() {
80 let token = sign_raw(&KEY, "repo-1", NOW);70 let token = sign_raw(&KEY, "repo-1", NOW);
81- // now == expires is already expired.
82 assert!(!verify_raw(&KEY, &token, "repo-1", NOW));71 assert!(!verify_raw(&KEY, &token, "repo-1", NOW));
83 assert!(!verify_raw(&KEY, &token, "repo-1", NOW + 1));72 assert!(!verify_raw(&KEY, &token, "repo-1", NOW + 1));
84 assert!(verify_raw(&KEY, &token, "repo-1", NOW - 1));73 assert!(verify_raw(&KEY, &token, "repo-1", NOW - 1));
crates/forge-core/src/reactions.rsmodified+0 -16
@@ -1,9 +1,5 @@
1-//! Emoji reactions: the fixed set a user can put on an issue, a pull request or a comment, and
2-//! the summaries the pages show. Stored as the short name (`+1`, `heart`, ...).
3-
4 use crate::model::Id;1 use crate::model::Id;
5 2
6-/// The fixed reaction set, in the order the pages list them.
7 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]3 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
8 pub enum Reaction {4 pub enum Reaction {
9 PlusOne,5 PlusOne,
@@ -17,7 +13,6 @@ pub enum Reaction {
17 }13 }
18 14
19 impl Reaction {15 impl Reaction {
20- /// Every reaction, in display order.
21 pub const ALL: [Reaction; 8] = [16 pub const ALL: [Reaction; 8] = [
22 Reaction::PlusOne,17 Reaction::PlusOne,
23 Reaction::MinusOne,18 Reaction::MinusOne,
@@ -29,7 +24,6 @@ impl Reaction {
29 Reaction::Eyes,24 Reaction::Eyes,
30 ];25 ];
31 26
32- /// The short name stored in the database and sent in forms.
33 pub fn name(self) -> &'static str {27 pub fn name(self) -> &'static str {
34 match self {28 match self {
35 Reaction::PlusOne => "+1",29 Reaction::PlusOne => "+1",
@@ -43,7 +37,6 @@ impl Reaction {
43 }37 }
44 }38 }
45 39
46- /// The glyph shown for the reaction.
47 pub fn emoji(self) -> &'static str {40 pub fn emoji(self) -> &'static str {
48 match self {41 match self {
49 Reaction::PlusOne => "\u{1f44d}",42 Reaction::PlusOne => "\u{1f44d}",
@@ -57,25 +50,20 @@ impl Reaction {
57 }50 }
58 }51 }
59 52
60- /// The reaction with this short name, or `None` for anything outside the set.
61 pub fn parse(name: &str) -> Option<Reaction> {53 pub fn parse(name: &str) -> Option<Reaction> {
62 Reaction::ALL.into_iter().find(|r| r.name() == name)54 Reaction::ALL.into_iter().find(|r| r.name() == name)
63 }55 }
64 }56 }
65 57
66-/// What a reaction is attached to. Pull requests are issue rows, so they use `Issue`.
67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]58 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
68 pub enum ReactionTarget {59 pub enum ReactionTarget {
69 Issue,60 Issue,
70 Comment,61 Comment,
71- /// A discussion (store/discussions.rs).
72 Discussion,62 Discussion,
73- /// A discussion comment or reply.
74 DiscussionComment,63 DiscussionComment,
75 }64 }
76 65
77 impl ReactionTarget {66 impl ReactionTarget {
78- /// The `target_kind` column value.
79 pub fn as_str(self) -> &'static str {67 pub fn as_str(self) -> &'static str {
80 match self {68 match self {
81 ReactionTarget::Issue => "issue",69 ReactionTarget::Issue => "issue",
@@ -86,8 +74,6 @@ impl ReactionTarget {
86 }74 }
87 }75 }
88 76
89-/// One reaction on one target: how many users chose it, whether the viewer did, and the first
90-/// usernames (at most ten, earliest reaction first).
91 #[derive(Debug, Clone, PartialEq, Eq)]77 #[derive(Debug, Clone, PartialEq, Eq)]
92 pub struct ReactionSummary {78 pub struct ReactionSummary {
93 pub reaction: Reaction,79 pub reaction: Reaction,
@@ -96,8 +82,6 @@ pub struct ReactionSummary {
96 pub users: Vec<String>,82 pub users: Vec<String>,
97 }83 }
98 84
99-/// Usernames kept per summary.
100 pub const SUMMARY_USERS: usize = 10;85 pub const SUMMARY_USERS: usize = 10;
101 86
102-/// Summaries of one target, keyed by the target id.
103 pub type ReactionMap = std::collections::HashMap<Id, Vec<ReactionSummary>>;87 pub type ReactionMap = std::collections::HashMap<Id, Vec<ReactionSummary>>;
crates/forge-core/src/releases.rsmodified+0 -20
@@ -1,26 +1,14 @@
1-//! Releases: a tag with a title, notes and optional downloadable assets. The stored shape is in
2-//! migrations/0020_releases.sql; the store functions live in store/releases.rs.
3-//!
4-//! A release names a git tag. The tag itself lives in git, so deleting a release keeps it.
5-//! Asset bytes live in the blob store under `assets/<asset id>`; only metadata is stored here.
6-
7 use crate::model::Id;1 use crate::model::Id;
8 2
9-/// Longest release title, in characters.
10 pub const MAX_TITLE_CHARS: usize = 200;3 pub const MAX_TITLE_CHARS: usize = 200;
11-/// Longest release body, in characters.
12 pub const MAX_BODY_CHARS: usize = 65_536;4 pub const MAX_BODY_CHARS: usize = 65_536;
13-/// Longest asset file name, in bytes. Names are ASCII, so bytes and characters agree.
14 pub const MAX_ASSET_NAME_LEN: usize = 200;5 pub const MAX_ASSET_NAME_LEN: usize = 200;
15 6
16-/// A release. `published_at` is set once it is first published and stays set; `draft` decides
17-/// visibility. Drafts are shown only to people with Write on the repo.
18 #[derive(Debug, Clone, PartialEq, Eq)]7 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub struct Release {8 pub struct Release {
20 pub id: Id,9 pub id: Id,
21 pub repo_id: Id,10 pub repo_id: Id,
22 pub tag: String,11 pub tag: String,
23- /// The commit the tag names when the release was made.
24 pub target_oid: String,12 pub target_oid: String,
25 pub title: String,13 pub title: String,
26 pub body: String,14 pub body: String,
@@ -32,7 +20,6 @@ pub struct Release {
32 pub published_at: Option<String>,20 pub published_at: Option<String>,
33 }21 }
34 22
35-/// A file attached to a release. `download_count` counts completed starts of downloads.
36 #[derive(Debug, Clone, PartialEq, Eq)]23 #[derive(Debug, Clone, PartialEq, Eq)]
37 pub struct ReleaseAsset {24 pub struct ReleaseAsset {
38 pub id: Id,25 pub id: Id,
@@ -46,7 +33,6 @@ pub struct ReleaseAsset {
46 pub created_at: String,33 pub created_at: String,
47 }34 }
48 35
49-/// Input for `Store::create_release`.
50 #[derive(Debug, Clone, Copy)]36 #[derive(Debug, Clone, Copy)]
51 pub struct NewRelease<'a> {37 pub struct NewRelease<'a> {
52 pub repo_id: &'a str,38 pub repo_id: &'a str,
@@ -59,7 +45,6 @@ pub struct NewRelease<'a> {
59 pub author_id: &'a str,45 pub author_id: &'a str,
60 }46 }
61 47
62-/// The editable fields of a release. The tag and its target are changed with `set_release_tag`.
63 #[derive(Debug, Clone, Copy)]48 #[derive(Debug, Clone, Copy)]
64 pub struct ReleaseEdit<'a> {49 pub struct ReleaseEdit<'a> {
65 pub title: &'a str,50 pub title: &'a str,
@@ -68,7 +53,6 @@ pub struct ReleaseEdit<'a> {
68 pub prerelease: bool,53 pub prerelease: bool,
69 }54 }
70 55
71-/// Input for `Store::add_asset`. The blob is already written under `assets/<id>`.
72 #[derive(Debug, Clone, Copy)]56 #[derive(Debug, Clone, Copy)]
73 pub struct NewAsset<'a> {57 pub struct NewAsset<'a> {
74 pub id: &'a str,58 pub id: &'a str,
@@ -80,8 +64,6 @@ pub struct NewAsset<'a> {
80 pub uploader_id: &'a str,64 pub uploader_id: &'a str,
81 }65 }
82 66
83-/// True for a file name that is safe in a `Content-Disposition` header and a URL segment: 1 to
84-/// [`MAX_ASSET_NAME_LEN`] of ASCII letters, digits, `.`, `-`, `_` or `+`, not starting with a dot.
85 pub fn valid_asset_name(name: &str) -> bool {67 pub fn valid_asset_name(name: &str) -> bool {
86 !name.is_empty()68 !name.is_empty()
87 && name.len() <= MAX_ASSET_NAME_LEN69 && name.len() <= MAX_ASSET_NAME_LEN
@@ -91,8 +73,6 @@ pub fn valid_asset_name(name: &str) -> bool {
91 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'+'))73 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'+'))
92 }74 }
93 75
94-/// The content type stored for an upload: a `type/subtype` token pair, or
95-/// `application/octet-stream` when the client sent nothing usable.
96 pub fn clean_content_type(raw: Option<&str>) -> String {76 pub fn clean_content_type(raw: Option<&str>) -> String {
97 let fallback = "application/octet-stream";77 let fallback = "application/octet-stream";
98 let Some(raw) = raw.map(str::trim) else {78 let Some(raw) = raw.map(str::trim) else {
crates/forge-core/src/reviews.rsmodified+0 -11
@@ -1,10 +1,6 @@
1-//! Pull request reviews and line comments. The stored shape is in migrations/0008_reviews.sql;
2-//! the store functions live in store/reviews.rs.
3-
4 use crate::error::{Error, Result};1 use crate::error::{Error, Result};
5 use crate::model::Id;2 use crate::model::Id;
6 3
7-/// State of a review. `Pending` is a draft visible only to its author.
8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]4 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9 pub enum ReviewState {5 pub enum ReviewState {
10 Pending,6 Pending,
@@ -41,8 +37,6 @@ impl std::str::FromStr for ReviewState {
41 }37 }
42 }38 }
43 39
44-/// Which side of the diff a comment is on: `Old` for deleted lines, `New` for added and context
45-/// lines.
46 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]40 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47 pub enum Side {41 pub enum Side {
48 Old,42 Old,
@@ -80,8 +74,6 @@ pub struct Review {
80 pub body: String,74 pub body: String,
81 pub commit_oid: String,75 pub commit_oid: String,
82 pub dismissed_reason: Option<String>,76 pub dismissed_reason: Option<String>,
83- /// The state the review had before it was dismissed (`Approved` or `ChangesRequested`). None
84- /// for reviews dismissed before this was recorded, and for reviews that were not dismissed.
85 pub dismissed_from: Option<ReviewState>,77 pub dismissed_from: Option<ReviewState>,
86 pub created_at: String,78 pub created_at: String,
87 pub submitted_at: Option<String>,79 pub submitted_at: Option<String>,
@@ -104,18 +96,15 @@ pub struct ReviewComment {
104 pub resolved: bool,96 pub resolved: bool,
105 pub created_at: String,97 pub created_at: String,
106 pub updated_at: String,98 pub updated_at: String,
107- /// True when the review this comment belongs to is still pending.
108 pub pending: bool,99 pub pending: bool,
109 }100 }
110 101
111-/// A root comment and its replies, oldest first.
112 #[derive(Debug, Clone, PartialEq)]102 #[derive(Debug, Clone, PartialEq)]
113 pub struct Thread {103 pub struct Thread {
114 pub root: ReviewComment,104 pub root: ReviewComment,
115 pub replies: Vec<ReviewComment>,105 pub replies: Vec<ReviewComment>,
116 }106 }
117 107
118-/// Who currently approves and who requests changes, by username.
119 #[derive(Debug, Clone, Default, PartialEq, Eq)]108 #[derive(Debug, Clone, Default, PartialEq, Eq)]
120 pub struct ReviewSummary {109 pub struct ReviewSummary {
121 pub approved_by: Vec<String>,110 pub approved_by: Vec<String>,
crates/forge-core/src/secret.rsmodified+0 -8
@@ -1,5 +1,3 @@
1-//! Instance key handling and XChaCha20-Poly1305 sealing of secrets at rest.
2-
3 use std::path::Path;1 use std::path::Path;
4 2
5 use base64::prelude::{BASE64_STANDARD, Engine as _};3 use base64::prelude::{BASE64_STANDARD, Engine as _};
@@ -11,7 +9,6 @@ use crate::error::{Error, Result};
11 const PREFIX: &str = "v1:";9 const PREFIX: &str = "v1:";
12 const NONCE_LEN: usize = 24;10 const NONCE_LEN: usize = 24;
13 11
14-/// Loads the 32-byte instance key at `path`, creating it (mode 0600) if missing.
15 pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> {12 pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> {
16 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {13 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
17 std::fs::create_dir_all(parent)?;14 std::fs::create_dir_all(parent)?;
@@ -76,9 +73,6 @@ fn read_key(path: &Path) -> Result<[u8; 32]> {
76 })73 })
77 }74 }
78 75
79-/// Seals `plaintext`. Output format: `"v1:" + base64(nonce || ciphertext)`.
80-///
81-/// Errors if the cipher rejects the input; the caller must not store plaintext instead.
82 pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {76 pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {
83 let mut nonce = [0u8; NONCE_LEN];77 let mut nonce = [0u8; NONCE_LEN];
84 rand::fill(&mut nonce);78 rand::fill(&mut nonce);
@@ -92,7 +86,6 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {
92 Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob)))86 Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob)))
93 }87 }
94 88
95-/// Opens a value produced by [`seal`].
96 pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> {89 pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> {
97 let encoded = sealed90 let encoded = sealed
98 .strip_prefix(PREFIX)91 .strip_prefix(PREFIX)
@@ -122,7 +115,6 @@ mod tests {
122 let sealed = seal(&key, b"hello secret").unwrap();115 let sealed = seal(&key, b"hello secret").unwrap();
123 assert!(sealed.starts_with("v1:"));116 assert!(sealed.starts_with("v1:"));
124 assert_eq!(open(&key, &sealed).unwrap(), b"hello secret");117 assert_eq!(open(&key, &sealed).unwrap(), b"hello secret");
125- // Fresh nonce each time.
126 assert_ne!(sealed, seal(&key, b"hello secret").unwrap());118 assert_ne!(sealed, seal(&key, b"hello secret").unwrap());
127 }119 }
128 120
crates/forge-core/src/store/account_tokens.rsmodified+0 -45
@@ -1,8 +1,3 @@
1-//! Account mail tokens: password reset, email verification and invites. A token is 32 random
2-//! bytes shown once in the mail link; only its sha256 is stored. Redeeming one is an UPDATE that
3-//! is guarded by `used_at IS NULL` and the expiry, so a link works at most once. Timestamps are
4-//! fixed-width UTC stamps, so expiry is a text comparison.
5-
6 use std::time::Duration;1 use std::time::Duration;
7 2
8 use super::finish;3 use super::finish;
@@ -16,16 +11,11 @@ use crate::names::normalize_name;
16 use crate::time::{now_stamp, stamp_after};11 use crate::time::{now_stamp, stamp_after};
17 use crate::token::{generate_token, hash_token};12 use crate::token::{generate_token, hash_token};
18 13
19-/// How long a password reset link works.
20 pub const RESET_TTL: Duration = Duration::from_secs(60 * 60);14 pub const RESET_TTL: Duration = Duration::from_secs(60 * 60);
21-/// How long an email verification link works.
22 pub const VERIFY_TTL: Duration = Duration::from_secs(24 * 60 * 60);15 pub const VERIFY_TTL: Duration = Duration::from_secs(24 * 60 * 60);
23-/// How long an invite link works.
24 pub const INVITE_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);16 pub const INVITE_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
25 17
26 impl Store {18 impl Store {
27- /// Mints a reset token for `user_id` and drops the user's unused ones, so only the newest
28- /// link works. Returns the plaintext token, which only the mail link carries.
29 pub async fn create_reset_token(&self, user_id: &str) -> Result<String> {19 pub async fn create_reset_token(&self, user_id: &str) -> Result<String> {
30 let token = generate_token();20 let token = generate_token();
31 let hash = hash_token(&token);21 let hash = hash_token(&token);
@@ -53,8 +43,6 @@ impl Store {
53 Ok(token)43 Ok(token)
54 }44 }
55 45
56- /// Redeems a reset token. Returns the id of its user, or `None` when the token is unknown,
57- /// used or expired. The UPDATE decides, so two redemptions of one link cannot both succeed.
58 pub async fn redeem_reset_token(&self, token: &str) -> Result<Option<String>> {46 pub async fn redeem_reset_token(&self, token: &str) -> Result<Option<String>> {
59 let hash = hash_token(token);47 let hash = hash_token(token);
60 let now = now_stamp();48 let now = now_stamp();
@@ -79,7 +67,6 @@ impl Store {
79 .await67 .await
80 }68 }
81 69
82- /// True while a reset token is unused and unexpired. Does not consume it.
83 pub async fn reset_token_is_live(&self, token: &str) -> Result<bool> {70 pub async fn reset_token_is_live(&self, token: &str) -> Result<bool> {
84 let conn = self.read_conn().await;71 let conn = self.read_conn().await;
85 let found = fetch_opt(72 let found = fetch_opt(
@@ -93,8 +80,6 @@ impl Store {
93 Ok(found.is_some())80 Ok(found.is_some())
94 }81 }
95 82
96- /// The user whose verified address is `email`, compared without case. Unverified addresses
97- /// never match, so a reset mail only goes to an address the account has proven it owns.
98 pub async fn verified_user_by_email(&self, email: &str) -> Result<Option<User>> {83 pub async fn verified_user_by_email(&self, email: &str) -> Result<Option<User>> {
99 let conn = self.read_conn().await;84 let conn = self.read_conn().await;
100 fetch_opt(85 fetch_opt(
@@ -109,7 +94,6 @@ impl Store {
109 .await94 .await
110 }95 }
111 96
112- /// Mints a verification token for `address` of `user_id`. Returns the plaintext token.
113 pub async fn create_verify_token(&self, user_id: &str, address: &str) -> Result<String> {97 pub async fn create_verify_token(&self, user_id: &str, address: &str) -> Result<String> {
114 let token = generate_token();98 let token = generate_token();
115 let hash = hash_token(&token);99 let hash = hash_token(&token);
@@ -137,8 +121,6 @@ impl Store {
137 Ok(token)121 Ok(token)
138 }122 }
139 123
140- /// Redeems a verification token and marks the address verified, as long as it is still the
141- /// user's address. Returns the user id, or `None` when the token is unusable or stale.
142 pub async fn redeem_verify_token(&self, token: &str) -> Result<Option<String>> {124 pub async fn redeem_verify_token(&self, token: &str) -> Result<Option<String>> {
143 let hash = hash_token(token);125 let hash = hash_token(token);
144 let now = now_stamp();126 let now = now_stamp();
@@ -179,8 +161,6 @@ impl Store {
179 finish(tx, outcome).await161 finish(tx, outcome).await
180 }162 }
181 163
182- /// Clears the verified mark. Called when the address changes, since the new one needs its
183- /// own link.
184 pub async fn clear_email_verified(&self, user_id: &str) -> Result<()> {164 pub async fn clear_email_verified(&self, user_id: &str) -> Result<()> {
185 let conn = self.inner.conn.lock().await;165 let conn = self.inner.conn.lock().await;
186 conn.execute(166 conn.execute(
@@ -192,7 +172,6 @@ impl Store {
192 Ok(())172 Ok(())
193 }173 }
194 174
195- /// Whether the user's current address has been verified.
196 pub async fn email_is_verified(&self, user_id: &str) -> Result<bool> {175 pub async fn email_is_verified(&self, user_id: &str) -> Result<bool> {
197 let conn = self.read_conn().await;176 let conn = self.read_conn().await;
198 let stamp = fetch_opt(177 let stamp = fetch_opt(
@@ -205,8 +184,6 @@ impl Store {
205 Ok(stamp.flatten().is_some())184 Ok(stamp.flatten().is_some())
206 }185 }
207 186
208- /// Creates an invite for `address`, dropping earlier unaccepted invites for it. Refused when
209- /// an account already uses the address. Returns the plaintext token.
210 pub async fn create_invite(&self, address: &str, invited_by: &str) -> Result<String> {187 pub async fn create_invite(&self, address: &str, invited_by: &str) -> Result<String> {
211 let token = generate_token();188 let token = generate_token();
212 let hash = hash_token(&token);189 let hash = hash_token(&token);
@@ -253,7 +230,6 @@ impl Store {
253 Ok(token)230 Ok(token)
254 }231 }
255 232
256- /// The address an invite is for, while the invite is unaccepted and unexpired.
257 pub async fn invite_email(&self, token: &str) -> Result<Option<String>> {233 pub async fn invite_email(&self, token: &str) -> Result<Option<String>> {
258 let conn = self.read_conn().await;234 let conn = self.read_conn().await;
259 fetch_opt(235 fetch_opt(
@@ -266,9 +242,6 @@ impl Store {
266 .await242 .await
267 }243 }
268 244
269- /// Accepts an invite and creates its account in one transaction. The invite's address is
270- /// verified at creation. Returns `None` when the invite is not usable. A taken username is a
271- /// `Conflict`, and the invite stays unused.
272 pub async fn accept_invite(245 pub async fn accept_invite(
273 &self,246 &self,
274 token: &str,247 token: &str,
@@ -358,7 +331,6 @@ mod tests {
358 .expect("user")331 .expect("user")
359 }332 }
360 333
361- /// Moves a token's expiry into the past, the way time passing would.
362 async fn expire(store: &Store, table: &str, token: &str) {334 async fn expire(store: &Store, table: &str, token: &str) {
363 let conn = store.inner.conn.lock().await;335 let conn = store.inner.conn.lock().await;
364 conn.execute(336 conn.execute(
@@ -369,14 +341,11 @@ mod tests {
369 .expect("expire");341 .expect("expire");
370 }342 }
371 343
372- /// Reset tokens redeem once, expired and unknown ones are refused, and a
373- /// new token replaces the unused one. Scenarios share one store and user.
374 #[tokio::test]344 #[tokio::test]
375 async fn reset_tokens() {345 async fn reset_tokens() {
376 let (_dir, store) = store().await;346 let (_dir, store) = store().await;
377 let user = new_user(&store, "tahinli", "tahinli@example.com").await;347 let user = new_user(&store, "tahinli", "tahinli@example.com").await;
378 348
379- // redeems once
380 let token = store.create_reset_token(&user.id).await.unwrap();349 let token = store.create_reset_token(&user.id).await.unwrap();
381 assert!(store.reset_token_is_live(&token).await.unwrap());350 assert!(store.reset_token_is_live(&token).await.unwrap());
382 assert_eq!(351 assert_eq!(
@@ -386,26 +355,21 @@ mod tests {
386 assert_eq!(store.redeem_reset_token(&token).await.unwrap(), None);355 assert_eq!(store.redeem_reset_token(&token).await.unwrap(), None);
387 assert!(!store.reset_token_is_live(&token).await.unwrap());356 assert!(!store.reset_token_is_live(&token).await.unwrap());
388 357
389- // expired and unknown are refused
390 let token = store.create_reset_token(&user.id).await.unwrap();358 let token = store.create_reset_token(&user.id).await.unwrap();
391 expire(&store, "password_reset_tokens", &token).await;359 expire(&store, "password_reset_tokens", &token).await;
392 assert_eq!(store.redeem_reset_token(&token).await.unwrap(), None);360 assert_eq!(store.redeem_reset_token(&token).await.unwrap(), None);
393 assert_eq!(store.redeem_reset_token("forge_nope").await.unwrap(), None);361 assert_eq!(store.redeem_reset_token("forge_nope").await.unwrap(), None);
394 362
395- // a new token replaces the unused one
396 let first = store.create_reset_token(&user.id).await.unwrap();363 let first = store.create_reset_token(&user.id).await.unwrap();
397 let second = store.create_reset_token(&user.id).await.unwrap();364 let second = store.create_reset_token(&user.id).await.unwrap();
398 assert_eq!(store.redeem_reset_token(&first).await.unwrap(), None);365 assert_eq!(store.redeem_reset_token(&first).await.unwrap(), None);
399 assert!(store.redeem_reset_token(&second).await.unwrap().is_some());366 assert!(store.redeem_reset_token(&second).await.unwrap().is_some());
400 }367 }
401 368
402- /// Email verification gates reset lookups, a token is void once the
403- /// address changes, and clearing the mark unverifies the address.
404 #[tokio::test]369 #[tokio::test]
405 async fn email_verification() {370 async fn email_verification() {
406 let (_dir, store) = store().await;371 let (_dir, store) = store().await;
407 372
408- // only a verified address matches a reset lookup
409 let user = new_user(&store, "tahinli", "tahinli@example.com").await;373 let user = new_user(&store, "tahinli", "tahinli@example.com").await;
410 assert!(374 assert!(
411 store375 store
@@ -431,7 +395,6 @@ mod tests {
431 .expect("verified user");395 .expect("verified user");
432 assert_eq!(found.id, user.id);396 assert_eq!(found.id, user.id);
433 397
434- // single use, and refused after the address changes
435 let carol = new_user(&store, "carol", "carol@example.com").await;398 let carol = new_user(&store, "carol", "carol@example.com").await;
436 let token = store399 let token = store
437 .create_verify_token(&carol.id, "carol@example.com")400 .create_verify_token(&carol.id, "carol@example.com")
@@ -450,7 +413,6 @@ mod tests {
450 assert!(store.redeem_verify_token(&fresh).await.unwrap().is_some());413 assert!(store.redeem_verify_token(&fresh).await.unwrap().is_some());
451 assert_eq!(store.redeem_verify_token(&fresh).await.unwrap(), None);414 assert_eq!(store.redeem_verify_token(&fresh).await.unwrap(), None);
452 415
453- // clearing the mark unverifies the address
454 let dave = new_user(&store, "dave", "dave@example.com").await;416 let dave = new_user(&store, "dave", "dave@example.com").await;
455 let token = store417 let token = store
456 .create_verify_token(&dave.id, "dave@example.com")418 .create_verify_token(&dave.id, "dave@example.com")
@@ -461,22 +423,17 @@ mod tests {
461 assert!(!store.email_is_verified(&dave.id).await.unwrap());423 assert!(!store.email_is_verified(&dave.id).await.unwrap());
462 }424 }
463 425
464- /// Invites: a taken address is refused, an invite makes one verified
465- /// account and is single use, a taken username leaves it unused, and an
466- /// expired invite is refused.
467 #[tokio::test]426 #[tokio::test]
468 async fn invites() {427 async fn invites() {
469 let (_dir, store) = store().await;428 let (_dir, store) = store().await;
470 let admin = new_user(&store, "tahinli", "tahinli@example.com").await;429 let admin = new_user(&store, "tahinli", "tahinli@example.com").await;
471 430
472- // a taken address is refused
473 let err = store431 let err = store
474 .create_invite("TAHINLI@example.com", &admin.id)432 .create_invite("TAHINLI@example.com", &admin.id)
475 .await433 .await
476 .expect_err("taken");434 .expect_err("taken");
477 assert!(matches!(err, Error::Conflict(_)));435 assert!(matches!(err, Error::Conflict(_)));
478 436
479- // one verified account, single use
480 let token = store437 let token = store
481 .create_invite("bob@example.com", &admin.id)438 .create_invite("bob@example.com", &admin.id)
482 .await439 .await
@@ -501,7 +458,6 @@ mod tests {
501 .is_none()458 .is_none()
502 );459 );
503 460
504- // a taken username leaves the invite unused
505 let token = store461 let token = store
506 .create_invite("gus@example.com", &admin.id)462 .create_invite("gus@example.com", &admin.id)
507 .await463 .await
@@ -513,7 +469,6 @@ mod tests {
513 assert!(matches!(err, Error::Conflict(_)));469 assert!(matches!(err, Error::Conflict(_)));
514 assert!(store.invite_email(&token).await.unwrap().is_some());470 assert!(store.invite_email(&token).await.unwrap().is_some());
515 471
516- // an expired invite is refused
517 let token = store472 let token = store
518 .create_invite("erin@example.com", &admin.id)473 .create_invite("erin@example.com", &admin.id)
519 .await474 .await
crates/forge-core/src/store/admin_alerts.rsmodified+0 -25
@@ -1,9 +1,3 @@
1-//! Admin alerts (migration 0058): the state of each alert condition, and the admins' inbox rows.
2-//!
3-//! A condition has a stable `key`. [`Store::raise_alert`] returns true only on the change from
4-//! "not active" to "active", and [`Store::resolve_alert`] only on "active" to "resolved", so a
5-//! condition that stays true is told once, and its end is told once.
6-
7 use turso::{Row, Value};1 use turso::{Row, Value};
8 2
9 use super::finish;3 use super::finish;
@@ -11,7 +5,6 @@ use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, new_id, text
11 use crate::error::Result;5 use crate::error::Result;
12 use crate::time::now_stamp;6 use crate::time::now_stamp;
13 7
14-/// A condition that is active now. Resolved alerts and one-shot events are not listed.
15 #[derive(Debug, Clone, PartialEq, Eq)]8 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub struct AdminAlert {9 pub struct AdminAlert {
17 pub key: String,10 pub key: String,
@@ -21,7 +14,6 @@ pub struct AdminAlert {
21 pub raised_at: String,14 pub raised_at: String,
22 }15 }
23 16
24-/// One admin's inbox row: a raised alert, or the message that it resolved.
25 #[derive(Debug, Clone, PartialEq, Eq)]17 #[derive(Debug, Clone, PartialEq, Eq)]
26 pub struct AdminNotice {18 pub struct AdminNotice {
27 pub id: String,19 pub id: String,
@@ -60,9 +52,6 @@ fn map_notice(row: &Row) -> Result<AdminNotice> {
60 }52 }
61 53
62 impl Store {54 impl Store {
63- /// Marks the condition `key` active. Returns true when it was not active before, which is
64- /// when the admins are told. An alert already active keeps its first `raised_at`; only its
65- /// detail is refreshed.
66 pub async fn raise_alert(55 pub async fn raise_alert(
67 &self,56 &self,
68 key: &str,57 key: &str,
@@ -117,8 +106,6 @@ impl Store {
117 finish(tx, outcome).await106 finish(tx, outcome).await
118 }107 }
119 108
120- /// Marks the condition `key` resolved. Returns the alert when it was active, so the caller
121- /// can say it is over, and `None` when there was nothing to resolve.
122 pub async fn resolve_alert(&self, key: &str) -> Result<Option<AdminAlert>> {109 pub async fn resolve_alert(&self, key: &str) -> Result<Option<AdminAlert>> {
123 let now = now_stamp();110 let now = now_stamp();
124 let conn = self.inner.conn.lock().await;111 let conn = self.inner.conn.lock().await;
@@ -147,8 +134,6 @@ impl Store {
147 finish(tx, outcome).await134 finish(tx, outcome).await
148 }135 }
149 136
150- /// Records a one-shot event under `key`. Returns true the first time only. An event is never
151- /// active, so it is not in [`Store::active_alerts`].
152 pub async fn record_alert_event(137 pub async fn record_alert_event(
153 &self,138 &self,
154 key: &str,139 key: &str,
@@ -175,7 +160,6 @@ impl Store {
175 Ok(changed > 0)160 Ok(changed > 0)
176 }161 }
177 162
178- /// Every alert that is active now, oldest first.
179 pub async fn active_alerts(&self) -> Result<Vec<AdminAlert>> {163 pub async fn active_alerts(&self) -> Result<Vec<AdminAlert>> {
180 let conn = self.read_conn().await;164 let conn = self.read_conn().await;
181 fetch_all(165 fetch_all(
@@ -188,7 +172,6 @@ impl Store {
188 .await172 .await
189 }173 }
190 174
191- /// The keys of the active alerts of one kind.
192 pub async fn active_alert_keys(&self, kind: &str) -> Result<Vec<String>> {175 pub async fn active_alert_keys(&self, kind: &str) -> Result<Vec<String>> {
193 let conn = self.read_conn().await;176 let conn = self.read_conn().await;
194 fetch_all(177 fetch_all(
@@ -200,7 +183,6 @@ impl Store {
200 .await183 .await
201 }184 }
202 185
203- /// Adds an inbox row for `user_id`.
204 pub async fn add_admin_notice(186 pub async fn add_admin_notice(
205 &self,187 &self,
206 user_id: &str,188 user_id: &str,
@@ -230,7 +212,6 @@ impl Store {
230 Ok(())212 Ok(())
231 }213 }
232 214
233- /// The user's alert inbox rows, newest first.
234 pub async fn list_admin_notices(215 pub async fn list_admin_notices(
235 &self,216 &self,
236 user_id: &str,217 user_id: &str,
@@ -266,7 +247,6 @@ impl Store {
266 .await247 .await
267 }248 }
268 249
269- /// Marks one of the user's alert rows read. Another user's row changes nothing.
270 pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> {250 pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> {
271 let conn = self.inner.conn.lock().await;251 let conn = self.inner.conn.lock().await;
272 conn.execute(252 conn.execute(
@@ -278,7 +258,6 @@ impl Store {
278 Ok(())258 Ok(())
279 }259 }
280 260
281- /// Marks all of the user's alert rows read.
282 pub async fn mark_all_admin_notices_read(&self, user_id: &str) -> Result<()> {261 pub async fn mark_all_admin_notices_read(&self, user_id: &str) -> Result<()> {
283 let conn = self.inner.conn.lock().await;262 let conn = self.inner.conn.lock().await;
284 conn.execute(263 conn.execute(
@@ -290,8 +269,6 @@ impl Store {
290 Ok(())269 Ok(())
291 }270 }
292 271
293- /// Deletes resolved and event rows and read inbox rows older than `before`, so the tables do
294- /// not grow without bound. Active alerts stay.
295 pub async fn prune_admin_alerts(&self, before: &str) -> Result<()> {272 pub async fn prune_admin_alerts(&self, before: &str) -> Result<()> {
296 let conn = self.inner.conn.lock().await;273 let conn = self.inner.conn.lock().await;
297 conn.execute(274 conn.execute(
@@ -375,8 +352,6 @@ mod tests {
375 assert!(store.active_alerts().await.unwrap().is_empty());352 assert!(store.active_alerts().await.unwrap().is_empty());
376 }353 }
377 354
378- // One store serves both. Events run first: they must not be active, and
379- // the raised alert below would otherwise show up in that empty check.
380 #[tokio::test]355 #[tokio::test]
381 async fn events_and_raised_alerts_share_one_store() {356 async fn events_and_raised_alerts_share_one_store() {
382 let (store, _dir) = store().await;357 let (store, _dir) = store().await;
crates/forge-core/src/store/advisories.rsmodified+0 -44
@@ -1,10 +1,3 @@
1-//! Advisory storage: the OSV rows of each ecosystem, the dependencies read from each repo's
2-//! lockfiles, and the alerts that match them.
3-//!
4-//! An alert is keyed by (repo, advisory, ecosystem, package, version). A scan opens alerts for new
5-//! matches, reopens a `fixed` alert whose match came back, and marks an `open` alert `fixed` when
6-//! its dependency is gone. `dismissed` alerts are left alone by scans.
7-
8 use std::collections::{BTreeSet, HashMap};1 use std::collections::{BTreeSet, HashMap};
9 2
10 use tokio::sync::mpsc;3 use tokio::sync::mpsc;
@@ -15,7 +8,6 @@ use crate::advisories::{Advisory, Dependency, Range, affects};
15 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
16 use crate::time::now_stamp;9 use crate::time::now_stamp;
17 10
18-/// The state of one alert.
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20 pub enum AlertState {12 pub enum AlertState {
21 Open,13 Open,
@@ -42,7 +34,6 @@ impl AlertState {
42 }34 }
43 }35 }
44 36
45-/// The identity of one alert within a repo.
46 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]37 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
47 pub struct AlertKey {38 pub struct AlertKey {
48 pub advisory_id: String,39 pub advisory_id: String,
@@ -51,7 +42,6 @@ pub struct AlertKey {
51 pub version: String,42 pub version: String,
52 }43 }
53 44
54-/// One alert, with the advisory's summary and severity for display.
55 #[derive(Debug, Clone, PartialEq, Eq)]45 #[derive(Debug, Clone, PartialEq, Eq)]
56 pub struct Alert {46 pub struct Alert {
57 pub key: AlertKey,47 pub key: AlertKey,
@@ -62,11 +52,9 @@ pub struct Alert {
62 pub updated_at: String,52 pub updated_at: String,
63 }53 }
64 54
65-/// One admin's inbox row for a repo: how many alerts a scan opened since the row was last read.
66 #[derive(Debug, Clone, PartialEq, Eq)]55 #[derive(Debug, Clone, PartialEq, Eq)]
67 pub struct AdvisoryNotice {56 pub struct AdvisoryNotice {
68 pub repo_id: String,57 pub repo_id: String,
69- /// The repo's owner and name, for the inbox row and its link.
70 pub repo_owner: String,58 pub repo_owner: String,
71 pub repo_name: String,59 pub repo_name: String,
72 pub new_alerts: u64,60 pub new_alerts: u64,
@@ -74,7 +62,6 @@ pub struct AdvisoryNotice {
74 pub updated_at: String,62 pub updated_at: String,
75 }63 }
76 64
77-/// What a scan changed: alerts opened (new or reopened) and alerts marked fixed.
78 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]65 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
79 pub struct ScanOutcome {66 pub struct ScanOutcome {
80 pub opened: usize,67 pub opened: usize,
@@ -132,11 +119,6 @@ fn key_params(repo_id: &str, key: &AlertKey) -> Vec<Value> {
132 }119 }
133 120
134 impl Store {121 impl Store {
135- /// Replaces every advisory of `ecosystem` with the advisories received from `batches`, in one
136- /// transaction, so the old rows stay until the last batch is in. The sender ends with `Ok(None)`
137- /// to commit; an `Err` item, or the channel closing without `Ok(None)` (the parser died), rolls
138- /// back. Rows for other ecosystems are not touched. Returns how many advisories were stored.
139- /// Callers rescan the repos afterwards.
140 pub async fn replace_advisories(122 pub async fn replace_advisories(
141 &self,123 &self,
142 ecosystem: &str,124 ecosystem: &str,
@@ -189,7 +171,6 @@ impl Store {
189 finish(tx, outcome).await171 finish(tx, outcome).await
190 }172 }
191 173
192- /// The advisories that name `package` in `ecosystem`.
193 pub async fn advisories_for_package(174 pub async fn advisories_for_package(
194 &self,175 &self,
195 ecosystem: &str,176 ecosystem: &str,
@@ -206,7 +187,6 @@ impl Store {
206 .await187 .await
207 }188 }
208 189
209- /// Every repo id, for a rescan after an advisory refresh.
210 pub async fn all_repo_ids(&self) -> Result<Vec<String>> {190 pub async fn all_repo_ids(&self) -> Result<Vec<String>> {
211 let conn = self.read_conn().await;191 let conn = self.read_conn().await;
212 fetch_all(&conn, "SELECT id FROM repos ORDER BY id", (), |row| {192 fetch_all(&conn, "SELECT id FROM repos ORDER BY id", (), |row| {
@@ -215,12 +195,8 @@ impl Store {
215 .await195 .await
216 }196 }
217 197
218- /// Records the dependencies of one repo and reconciles its alerts with the advisories that
219- /// match them. The dependency rows are replaced; the alerts are opened, reopened or marked
220- /// fixed as described in the module docs.
221 pub async fn scan_repo(&self, repo_id: &str, deps: &[Dependency]) -> Result<ScanOutcome> {198 pub async fn scan_repo(&self, repo_id: &str, deps: &[Dependency]) -> Result<ScanOutcome> {
222 let unique: BTreeSet<&Dependency> = deps.iter().collect();199 let unique: BTreeSet<&Dependency> = deps.iter().collect();
223- // Matches are computed before the write lock, from the read pool.
224 let mut by_package: HashMap<(String, String), Vec<Advisory>> = HashMap::new();200 let mut by_package: HashMap<(String, String), Vec<Advisory>> = HashMap::new();
225 let mut matched: BTreeSet<AlertKey> = BTreeSet::new();201 let mut matched: BTreeSet<AlertKey> = BTreeSet::new();
226 for dep in &unique {202 for dep in &unique {
@@ -320,7 +296,6 @@ impl Store {
320 finish(tx, outcome).await296 finish(tx, outcome).await
321 }297 }
322 298
323- /// Moves one alert from `from` to `to`. Returns false when the alert is not in `from`.
324 pub async fn set_alert_state(299 pub async fn set_alert_state(
325 &self,300 &self,
326 repo_id: &str,301 repo_id: &str,
@@ -340,7 +315,6 @@ impl Store {
340 finish(tx, outcome).await315 finish(tx, outcome).await
341 }316 }
342 317
343- /// The alerts of a repo, open first, with the advisory's summary and severity.
344 pub async fn list_alerts(&self, repo_id: &str) -> Result<Vec<Alert>> {318 pub async fn list_alerts(&self, repo_id: &str) -> Result<Vec<Alert>> {
345 let conn = self.read_conn().await;319 let conn = self.read_conn().await;
346 fetch_all(320 fetch_all(
@@ -359,7 +333,6 @@ impl Store {
359 .await333 .await
360 }334 }
361 335
362- /// How many dependency rows the last scan of a repo recorded.
363 pub async fn dependency_count(&self, repo_id: &str) -> Result<u64> {336 pub async fn dependency_count(&self, repo_id: &str) -> Result<u64> {
364 let conn = self.read_conn().await;337 let conn = self.read_conn().await;
365 let mut rows = conn338 let mut rows = conn
@@ -379,8 +352,6 @@ impl Store {
379 }352 }
380 353
381 impl Store {354 impl Store {
382- /// Adds `new_alerts` to the admin's inbox row for `repo_id` and marks it unread. While the row
383- /// is unread the counts add up; once read, a new count starts it again.
384 pub async fn notify_new_alerts(355 pub async fn notify_new_alerts(
385 &self,356 &self,
386 user_id: &str,357 user_id: &str,
@@ -410,8 +381,6 @@ impl Store {
410 Ok(())381 Ok(())
411 }382 }
412 383
413- /// The user's inbox rows for repos with security alerts, newest first. `unread_only`, `before`
414- /// and `limit` mean what they mean in `list_notifications`.
415 pub async fn list_advisory_notifications(384 pub async fn list_advisory_notifications(
416 &self,385 &self,
417 user_id: &str,386 user_id: &str,
@@ -434,7 +403,6 @@ impl Store {
434 fetch_all(&conn, &sql, params, map_advisory_notice).await403 fetch_all(&conn, &sql, params, map_advisory_notice).await
435 }404 }
436 405
437- /// The user's inbox row for one repo's alerts, if there is one.
438 pub async fn advisory_notification(406 pub async fn advisory_notification(
439 &self,407 &self,
440 user_id: &str,408 user_id: &str,
@@ -450,7 +418,6 @@ impl Store {
450 .await418 .await
451 }419 }
452 420
453- /// Marks the user's inbox row for one repo's alerts read. Another user's row changes nothing.
454 pub async fn mark_advisory_notification_read(421 pub async fn mark_advisory_notification_read(
455 &self,422 &self,
456 user_id: &str,423 user_id: &str,
@@ -466,7 +433,6 @@ impl Store {
466 Ok(())433 Ok(())
467 }434 }
468 435
469- /// Marks the user's unread alert rows read, in one repo when `repo_id` is given, otherwise all.
470 pub async fn mark_all_advisory_notifications_read(436 pub async fn mark_all_advisory_notifications_read(
471 &self,437 &self,
472 user_id: &str,438 user_id: &str,
@@ -494,8 +460,6 @@ impl Store {
494 }460 }
495 }461 }
496 462
497-/// Inbox rows of repos with alerts, joined with the repo and its owner. `?` placeholders are
498-/// appended by the callers.
499 const ADVISORY_NOTICE_SELECT: &str = "SELECT n.repo_id, o.username, r.name, n.new_alerts, \463 const ADVISORY_NOTICE_SELECT: &str = "SELECT n.repo_id, o.username, r.name, n.new_alerts, \
500 n.unread, n.updated_at FROM advisory_notifications n \464 n.unread, n.updated_at FROM advisory_notifications n \
501 JOIN repos r ON r.id = n.repo_id \465 JOIN repos r ON r.id = n.repo_id \
@@ -543,7 +507,6 @@ mod tests {
543 use crate::store::Store;507 use crate::store::Store;
544 508
545 impl Store {509 impl Store {
546- /// Replaces `ecosystem` with `advisories` sent as one batch.
547 async fn replace_in_one_batch(510 async fn replace_in_one_batch(
548 &self,511 &self,
549 ecosystem: &str,512 ecosystem: &str,
@@ -594,14 +557,11 @@ mod tests {
594 (store, repo.id)557 (store, repo.id)
595 }558 }
596 559
597- // Advisories are global, so each block replaces the advisory set it needs
598- // before scanning. The per-repo alert checks use their own repo.
599 #[tokio::test]560 #[tokio::test]
600 async fn scans_reconcile_alerts_and_replace_per_ecosystem() {561 async fn scans_reconcile_alerts_and_replace_per_ecosystem() {
601 let dir = tempfile::tempdir().unwrap();562 let dir = tempfile::tempdir().unwrap();
602 let (store, repo) = store_with_repo(&dir).await;563 let (store, repo) = store_with_repo(&dir).await;
603 564
604- // A scan opens alerts, closes fixed ones, and keeps dismissed ones.
605 store565 store
606 .replace_in_one_batch(566 .replace_in_one_batch(
607 "crates.io",567 "crates.io",
@@ -631,7 +591,6 @@ mod tests {
631 "two dependencies"591 "two dependencies"
632 );592 );
633 593
634- // Upgrading `other` past its fix closes its alert. `old` stays vulnerable.
635 let second = store594 let second = store
636 .scan_repo(&repo, &[dep("old", "1.0.0"), dep("other", "2.0.0")])595 .scan_repo(&repo, &[dep("old", "1.0.0"), dep("other", "2.0.0")])
637 .await596 .await
@@ -672,7 +631,6 @@ mod tests {
672 .unwrap();631 .unwrap();
673 assert_eq!(fixed.state, AlertState::Fixed, "fixed alert");632 assert_eq!(fixed.state, AlertState::Fixed, "fixed alert");
674 633
675- // Dismiss, then a scan keeps it dismissed; a reopen moves it back.
676 assert!(634 assert!(
677 store635 store
678 .set_alert_state(&repo, &open.key, AlertState::Open, AlertState::Dismissed)636 .set_alert_state(&repo, &open.key, AlertState::Open, AlertState::Dismissed)
@@ -707,7 +665,6 @@ mod tests {
707 "reopen applied"665 "reopen applied"
708 );666 );
709 667
710- // A fixed alert reopens when the vulnerable match returns (own repo).
711 let owner = store.repo_by_id(&repo).await.unwrap().unwrap().owner_id;668 let owner = store.repo_by_id(&repo).await.unwrap().unwrap().owner_id;
712 let back = store669 let back = store
713 .create_repo(&owner, "back", "", crate::Visibility::Private, "main")670 .create_repo(&owner, "back", "", crate::Visibility::Private, "main")
@@ -742,7 +699,6 @@ mod tests {
742 assert_eq!(alerts.len(), 2, "alert count on the back repo");699 assert_eq!(alerts.len(), 2, "alert count on the back repo");
743 assert_eq!(alerts[0].state, AlertState::Open, "reopened alert is open");700 assert_eq!(alerts[0].state, AlertState::Open, "reopened alert is open");
744 701
745- // Replacing advisories for one ecosystem leaves the others alone.
746 store702 store
747 .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-4", "a", "2.0.0")])703 .replace_in_one_batch("crates.io", &[advisory("RUSTSEC-4", "a", "2.0.0")])
748 .await704 .await
crates/forge-core/src/store/attachments.rsmodified+0 -7
@@ -1,14 +1,9 @@
1-//! Metadata of files attached through the markdown editors. The bytes are in blob storage under
2-//! `attachments/<id>`; a row ties the file to the repo it was uploaded in, which is what the
3-//! download access check follows (a file is as visible as its repo).
4-
5 use serde::Serialize;1 use serde::Serialize;
6 2
7 use super::{Store, col_int, col_text, db_err, fetch_opt};3 use super::{Store, col_int, col_text, db_err, fetch_opt};
8 use crate::error::Result;4 use crate::error::Result;
9 use crate::time::now_stamp;5 use crate::time::now_stamp;
10 6
11-/// One stored attachment.
12 #[derive(Debug, Clone, Serialize)]7 #[derive(Debug, Clone, Serialize)]
13 pub struct Attachment {8 pub struct Attachment {
14 pub id: String,9 pub id: String,
@@ -22,7 +17,6 @@ pub struct Attachment {
22 }17 }
23 18
24 impl Store {19 impl Store {
25- /// Records an attachment whose blob is already stored under `id`.
26 #[allow(clippy::too_many_arguments)]20 #[allow(clippy::too_many_arguments)]
27 pub async fn add_attachment(21 pub async fn add_attachment(
28 &self,22 &self,
@@ -64,7 +58,6 @@ impl Store {
64 })58 })
65 }59 }
66 60
67- /// The attachment `id`, if any. The caller checks the viewer can read `repo_id`.
68 pub async fn attachment(&self, id: &str) -> Result<Option<Attachment>> {61 pub async fn attachment(&self, id: &str) -> Result<Option<Attachment>> {
69 let conn = self.read_conn().await;62 let conn = self.read_conn().await;
70 fetch_opt(63 fetch_opt(
crates/forge-core/src/store/audit.rsmodified+0 -12
@@ -1,5 +1,3 @@
1-//! Audit log storage. Append-only: the only delete is the retention purge.
2-
3 use turso::{Row, Value};1 use turso::{Row, Value};
4 2
5 use super::{Store, col_opt_text, col_text, db_err, fetch_all};3 use super::{Store, col_opt_text, col_text, db_err, fetch_all};
@@ -8,7 +6,6 @@ use crate::error::{Error, Result};
8 6
9 const AUDIT_COLS: &str = "id, at, actor_id, actor_name, action, target_kind, target_id, \7 const AUDIT_COLS: &str = "id, at, actor_id, actor_name, action, target_kind, target_id, \
10 target_name, ip, data";8 target_name, ip, data";
11-/// Largest page `list_audit` returns, whatever the caller asks for.
12 const MAX_AUDIT_PAGE: u32 = 200;9 const MAX_AUDIT_PAGE: u32 = 200;
13 10
14 fn map_audit(row: &Row) -> Result<AuditEntry> {11 fn map_audit(row: &Row) -> Result<AuditEntry> {
@@ -28,8 +25,6 @@ fn map_audit(row: &Row) -> Result<AuditEntry> {
28 })25 })
29 }26 }
30 27
31-/// The WHERE clause and its parameters for `filter` and an optional cursor, shared by the
32-/// listings and the count so they select the same entries.
33 fn audit_where(filter: &AuditFilter, before: Option<&AuditCursor>) -> (String, Vec<Value>) {28 fn audit_where(filter: &AuditFilter, before: Option<&AuditCursor>) -> (String, Vec<Value>) {
34 let mut clauses: Vec<&str> = Vec::new();29 let mut clauses: Vec<&str> = Vec::new();
35 let mut params: Vec<Value> = Vec::new();30 let mut params: Vec<Value> = Vec::new();
@@ -77,7 +72,6 @@ fn audit_where(filter: &AuditFilter, before: Option<&AuditCursor>) -> (String, V
77 }72 }
78 73
79 impl Store {74 impl Store {
80- /// Appends one entry. Nothing else in the store writes to `audit_log`.
81 pub async fn record_audit(&self, entry: &AuditEntry) -> Result<()> {75 pub async fn record_audit(&self, entry: &AuditEntry) -> Result<()> {
82 let actor_id = match &entry.actor_id {76 let actor_id = match &entry.actor_id {
83 Some(id) => Value::Text(id.clone()),77 Some(id) => Value::Text(id.clone()),
@@ -106,8 +100,6 @@ impl Store {
106 Ok(())100 Ok(())
107 }101 }
108 102
109- /// Entries matching `filter`, newest first. `before` continues after the last entry of the
110- /// previous page. `limit` is clamped to 1..=200.
111 pub async fn list_audit(103 pub async fn list_audit(
112 &self,104 &self,
113 filter: &AuditFilter,105 filter: &AuditFilter,
@@ -123,8 +115,6 @@ impl Store {
123 fetch_all(&conn, &sql, params, map_audit).await115 fetch_all(&conn, &sql, params, map_audit).await
124 }116 }
125 117
126- /// Entries matching `filter` in the same order as [`Store::list_audit`], skipping `offset`
127- /// entries first. For numbered pages. `limit` is clamped to 1..=200.
128 pub async fn list_audit_page(118 pub async fn list_audit_page(
129 &self,119 &self,
130 filter: &AuditFilter,120 filter: &AuditFilter,
@@ -142,8 +132,6 @@ impl Store {
142 fetch_all(&conn, &sql, params, map_audit).await132 fetch_all(&conn, &sql, params, map_audit).await
143 }133 }
144 134
145- /// Retention: deletes entries stamped before `cutoff` (an RFC 3339 UTC stamp). Returns the
146- /// number of entries removed. This is the only delete on the audit log.
147 pub async fn purge_audit_before(&self, cutoff: &str) -> Result<u64> {135 pub async fn purge_audit_before(&self, cutoff: &str) -> Result<u64> {
148 let conn = self.inner.conn.lock().await;136 let conn = self.inner.conn.lock().await;
149 conn.execute("DELETE FROM audit_log WHERE at < ?1", (cutoff.to_string(),))137 conn.execute("DELETE FROM audit_log WHERE at < ?1", (cutoff.to_string(),))
crates/forge-core/src/store/backup_runs.rsmodified+0 -17
@@ -1,6 +1,3 @@
1-//! Records of backup and fsck runs, shown on `/admin/backups`. The scheduler and the admin
2-//! actions write them; nothing deletes them.
3-
4 use turso::{Row, Value};1 use turso::{Row, Value};
5 2
6 use super::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all, new_id};3 use super::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all, new_id};
@@ -8,10 +5,8 @@ use crate::error::{Error, Result};
8 use crate::time::now_stamp;5 use crate::time::now_stamp;
9 6
10 const RUN_COLS: &str = "id, kind, started_at, finished_at, ok, path, bytes, error, \"trigger\"";7 const RUN_COLS: &str = "id, kind, started_at, finished_at, ok, path, bytes, error, \"trigger\"";
11-/// Largest page `recent_runs` returns.
12 const MAX_RUNS: u32 = 200;8 const MAX_RUNS: u32 = 200;
13 9
14-/// What a run did.
15 #[derive(Debug, Clone, Copy, PartialEq, Eq)]10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16 pub enum RunKind {11 pub enum RunKind {
17 Backup,12 Backup,
@@ -35,7 +30,6 @@ impl RunKind {
35 }30 }
36 }31 }
37 32
38-/// What started a run.
39 #[derive(Debug, Clone, Copy, PartialEq, Eq)]33 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
40 pub enum RunTrigger {34 pub enum RunTrigger {
41 Schedule,35 Schedule,
@@ -62,7 +56,6 @@ impl RunTrigger {
62 }56 }
63 }57 }
64 58
65-/// One row of `backup_runs`. `finished_at` and `ok` are `None` while the run is in progress.
66 #[derive(Debug, Clone, PartialEq, Eq)]59 #[derive(Debug, Clone, PartialEq, Eq)]
67 pub struct BackupRun {60 pub struct BackupRun {
68 pub id: String,61 pub id: String,
@@ -98,8 +91,6 @@ fn map_run(row: &Row) -> Result<BackupRun> {
98 }91 }
99 92
100 impl Store {93 impl Store {
101- /// Records the start of a run and returns its id. The row stays unfinished until
102- /// [`Store::finish_run`] is called.
103 pub async fn start_run(&self, kind: RunKind, trigger: RunTrigger) -> Result<String> {94 pub async fn start_run(&self, kind: RunKind, trigger: RunTrigger) -> Result<String> {
104 let id = new_id();95 let id = new_id();
105 let conn = self.inner.conn.lock().await;96 let conn = self.inner.conn.lock().await;
@@ -118,8 +109,6 @@ impl Store {
118 Ok(id)109 Ok(id)
119 }110 }
120 111
121- /// Marks run `id` finished. `path` and `bytes` describe a finished backup set; `error` holds
122- /// the first failure when `ok` is false.
123 pub async fn finish_run(112 pub async fn finish_run(
124 &self,113 &self,
125 id: &str,114 id: &str,
@@ -156,7 +145,6 @@ impl Store {
156 Ok(())145 Ok(())
157 }146 }
158 147
159- /// The newest `limit` runs of any kind, newest first. `limit` is clamped to 1..=200.
160 pub async fn recent_runs(&self, limit: u32) -> Result<Vec<BackupRun>> {148 pub async fn recent_runs(&self, limit: u32) -> Result<Vec<BackupRun>> {
161 let sql = format!(149 let sql = format!(
162 "SELECT {RUN_COLS} FROM backup_runs ORDER BY started_at DESC, id DESC LIMIT ?1"150 "SELECT {RUN_COLS} FROM backup_runs ORDER BY started_at DESC, id DESC LIMIT ?1"
@@ -165,12 +153,10 @@ impl Store {
165 fetch_all(&conn, &sql, (i64::from(limit.clamp(1, MAX_RUNS)),), map_run).await153 fetch_all(&conn, &sql, (i64::from(limit.clamp(1, MAX_RUNS)),), map_run).await
166 }154 }
167 155
168- /// The newest run of `kind` that finished with `ok`, if any.
169 pub async fn last_ok(&self, kind: RunKind) -> Result<Option<BackupRun>> {156 pub async fn last_ok(&self, kind: RunKind) -> Result<Option<BackupRun>> {
170 self.latest_run(kind, true).await157 self.latest_run(kind, true).await
171 }158 }
172 159
173- /// The newest run of `kind`, whatever its outcome.
174 pub async fn last_run(&self, kind: RunKind) -> Result<Option<BackupRun>> {160 pub async fn last_run(&self, kind: RunKind) -> Result<Option<BackupRun>> {
175 self.latest_run(kind, false).await161 self.latest_run(kind, false).await
176 }162 }
@@ -186,7 +172,6 @@ impl Store {
186 Ok(rows.into_iter().next())172 Ok(rows.into_iter().next())
187 }173 }
188 174
189- /// Ids of every repo, in id order. The fsck job walks this list.
190 pub async fn repo_ids(&self) -> Result<Vec<String>> {175 pub async fn repo_ids(&self) -> Result<Vec<String>> {
191 let conn = self.read_conn().await;176 let conn = self.read_conn().await;
192 fetch_all(&conn, "SELECT id FROM repos ORDER BY id", (), |row| {177 fetch_all(&conn, "SELECT id FROM repos ORDER BY id", (), |row| {
@@ -212,7 +197,6 @@ mod tests {
212 async fn start_and_finish_round_trip() {197 async fn start_and_finish_round_trip() {
213 let (_dir, store) = store().await;198 let (_dir, store) = store().await;
214 199
215- // The repo list starts empty and follows repo creation.
216 assert!(200 assert!(
217 store.repo_ids().await.expect("ids").is_empty(),201 store.repo_ids().await.expect("ids").is_empty(),
218 "no repos yet"202 "no repos yet"
@@ -237,7 +221,6 @@ mod tests {
237 "one repo listed"221 "one repo listed"
238 );222 );
239 223
240- // A run starts unfinished, then finishes with its outcome.
241 let id = store224 let id = store
242 .start_run(RunKind::Backup, RunTrigger::Manual)225 .start_run(RunKind::Backup, RunTrigger::Manual)
243 .await226 .await
crates/forge-core/src/store/ci.rsmodified+0 -144
@@ -1,9 +1,3 @@
1-//! CI store: runners, registration tokens, runs, jobs, artifacts and sealed repo secrets.
2-//!
3-//! Pure SELECTs run on `read_conn()`. Writes, and anything that reads then writes, run on the
4-//! writer. Multi-step changes (create, claim, finish, cancel, reap, purge) run in one transaction.
5-//! The `needs` and `runs_on` arrays are read out of the JobSpec JSON in `spec_json`.
6-
7 use std::collections::{BTreeMap, BTreeSet};1 use std::collections::{BTreeMap, BTreeSet};
8 use std::time::Duration;2 use std::time::Duration;
9 3
@@ -35,7 +29,6 @@ const RUNNER_COLS: &str = "id, name, labels, created_at, last_seen_at, disabled,
35 (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \29 (SELECT COUNT(*) FROM ci_jobs WHERE ci_jobs.runner_id = ci_runners.id AND ci_jobs.state = 'running'), \
36 reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \30 reported_build, reported_boot_id, restart_mode, restart_requested_at, reported_capabilities, \
37 reported_memory_budget, reported_memory_free, reported_memory_reserve";31 reported_memory_budget, reported_memory_free, reported_memory_reserve";
38-/// The job columns of `runner_jobs`, then the run's number and the repo's owner and name.
39 const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \32 const RUNNER_JOB_COLS: &str = "j.id, j.run_id, j.name, j.spec, j.state, j.runner_id, j.exit_code, \
40 j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \33 j.message, j.queued_at, j.started_at, j.finished_at, j.heartbeat_at, j.cancel_requested, \
41 j.log_bytes, j.oom_kills, r.number, u.username, p.name";34 j.log_bytes, j.oom_kills, r.number, u.username, p.name";
@@ -43,11 +36,8 @@ const RUNNER_JOB_FROM: &str = "FROM ci_jobs j JOIN ci_runs r ON r.id = j.run_id
43 JOIN repos p ON p.id = r.repo_id JOIN users u ON u.id = p.owner_id";36 JOIN repos p ON p.id = r.repo_id JOIN users u ON u.id = p.owner_id";
44 const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at";37 const ARTIFACT_COLS: &str = "id, job_id, name, size, sha256, created_at";
45 38
46-/// Longest runner name, in bytes.
47 const MAX_RUNNER_NAME: usize = 100;39 const MAX_RUNNER_NAME: usize = 100;
48-/// Longest runner label, in bytes.
49 const MAX_LABEL: usize = 64;40 const MAX_LABEL: usize = 64;
50-/// Longest page `list_runs` returns.
51 const MAX_PER_PAGE: u32 = 100;41 const MAX_PER_PAGE: u32 = 100;
52 42
53 fn map_runner(row: &Row) -> Result<CiRunner> {43 fn map_runner(row: &Row) -> Result<CiRunner> {
@@ -92,14 +82,12 @@ fn map_runner(row: &Row) -> Result<CiRunner> {
92 })82 })
93 }83 }
94 84
95-/// A NULL-able column holding a flat JSON object. Bad or missing JSON reads as empty.
96 fn json_map(row: &Row, i: usize) -> Result<BTreeMap<String, serde_json::Value>> {85 fn json_map(row: &Row, i: usize) -> Result<BTreeMap<String, serde_json::Value>> {
97 Ok(col_opt_text(row, i)?86 Ok(col_opt_text(row, i)?
98 .and_then(|text| serde_json::from_str(&text).ok())87 .and_then(|text| serde_json::from_str(&text).ok())
99 .unwrap_or_default())88 .unwrap_or_default())
100 }89 }
101 90
102-/// A NULL-able integer column that holds a count.
103 fn opt_u32(row: &Row, i: usize) -> Result<Option<u32>> {91 fn opt_u32(row: &Row, i: usize) -> Result<Option<u32>> {
104 Ok(col_opt_int(row, i)?.and_then(|n| u32::try_from(n).ok()))92 Ok(col_opt_int(row, i)?.and_then(|n| u32::try_from(n).ok()))
105 }93 }
@@ -161,7 +149,6 @@ fn map_artifact(row: &Row) -> Result<CiArtifact> {
161 })149 })
162 }150 }
163 151
164-/// `spec` with its `needs` array replaced. Malformed input is returned as it is.
165 fn spec_with_needs(spec: &str, needs: &[String]) -> String {152 fn spec_with_needs(spec: &str, needs: &[String]) -> String {
166 match serde_json::from_str::<serde_json::Value>(spec) {153 match serde_json::from_str::<serde_json::Value>(spec) {
167 Ok(mut value) if value.is_object() => {154 Ok(mut value) if value.is_object() => {
@@ -172,7 +159,6 @@ fn spec_with_needs(spec: &str, needs: &[String]) -> String {
172 }159 }
173 }160 }
174 161
175-/// The `needs` array of a JobSpec. Missing or malformed input gives no needs.
176 fn spec_needs(spec: &str) -> Vec<String> {162 fn spec_needs(spec: &str) -> Vec<String> {
177 serde_json::from_str::<serde_json::Value>(spec)163 serde_json::from_str::<serde_json::Value>(spec)
178 .ok()164 .ok()
@@ -189,7 +175,6 @@ fn spec_needs(spec: &str) -> Vec<String> {
189 .unwrap_or_default()175 .unwrap_or_default()
190 }176 }
191 177
192-/// The `memory` a job's stored spec declares, in bytes.
193 fn declared_memory(spec: &str) -> Option<u64> {178 fn declared_memory(spec: &str) -> Option<u64> {
194 serde_json::from_str::<serde_json::Value>(spec)179 serde_json::from_str::<serde_json::Value>(spec)
195 .ok()?180 .ok()?
@@ -197,8 +182,6 @@ fn declared_memory(spec: &str) -> Option<u64> {
197 .as_u64()182 .as_u64()
198 }183 }
199 184
200-/// True when every label in the spec's `runs_on` is one of the runner's labels. A missing
201-/// `runs_on` means no requirement. A malformed spec is never claimable.
202 fn runs_on_covered(spec: &str, labels: &[String]) -> bool {185 fn runs_on_covered(spec: &str, labels: &[String]) -> bool {
203 let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else {186 let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else {
204 return false;187 return false;
@@ -213,7 +196,6 @@ fn runs_on_covered(spec: &str, labels: &[String]) -> bool {
213 }196 }
214 }197 }
215 198
216-/// The `runs_on` labels of the spec that `labels` lack. Nothing for a malformed spec.
217 fn runs_on_missing(spec: &str, labels: &[String]) -> Vec<String> {199 fn runs_on_missing(spec: &str, labels: &[String]) -> Vec<String> {
218 let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else {200 let Ok(value) = serde_json::from_str::<serde_json::Value>(spec) else {
219 return Vec::new();201 return Vec::new();
@@ -232,7 +214,6 @@ fn runs_on_missing(spec: &str, labels: &[String]) -> Vec<String> {
232 .unwrap_or_default()214 .unwrap_or_default()
233 }215 }
234 216
235-/// Secret names follow the JobSpec rule: `^[A-Z_][A-Z0-9_]{0,63}$`.
236 fn validate_secret_name(name: &str) -> Result<()> {217 fn validate_secret_name(name: &str) -> Result<()> {
237 let first_ok = name218 let first_ok = name
238 .bytes()219 .bytes()
@@ -290,9 +271,6 @@ async fn load_runner(conn: &Connection, id: &str) -> Result<Option<CiRunner>> {
290 .await271 .await
291 }272 }
292 273
293-/// Moves blocked jobs on. A blocked job whose needs all succeeded becomes `Queued`. One whose
294-/// need ended without success, or is missing, becomes `Skipped`. Repeats until nothing changes,
295-/// so skips cascade to every dependant.
296 async fn propagate(conn: &Connection, run_id: &str, now: &str) -> Result<()> {274 async fn propagate(conn: &Connection, run_id: &str, now: &str) -> Result<()> {
297 let jobs = jobs_of_run(conn, run_id).await?;275 let jobs = jobs_of_run(conn, run_id).await?;
298 let needs: Vec<Vec<String>> = jobs.iter().map(|j| spec_needs(&j.spec_json)).collect();276 let needs: Vec<Vec<String>> = jobs.iter().map(|j| spec_needs(&j.spec_json)).collect();
@@ -346,9 +324,6 @@ async fn propagate(conn: &Connection, run_id: &str, now: &str) -> Result<()> {
346 }324 }
347 }325 }
348 326
349-/// Recomputes a live run's state from its jobs: any running, queued or blocked job makes it
350-/// `Running`; otherwise `Failure` if any job failed or errored, `Cancelled` if any was cancelled,
351-/// else `Success`. Terminal runs and config-error runs are left alone.
352 async fn recompute_run(conn: &Connection, run_id: &str, now: &str) -> Result<()> {327 async fn recompute_run(conn: &Connection, run_id: &str, now: &str) -> Result<()> {
353 let run = load_run(conn, run_id).await?.ok_or(Error::NotFound)?;328 let run = load_run(conn, run_id).await?.ok_or(Error::NotFound)?;
354 if run.state.is_terminal() || run.config_error.is_some() {329 if run.state.is_terminal() || run.config_error.is_some() {
@@ -439,8 +414,6 @@ impl Store {
439 Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())414 Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())
440 }415 }
441 416
442- /// Creates a single-use registration token valid for `ttl_hours`. Returns the plaintext,
443- /// which is shown once. Only its sha256 is stored.
444 pub async fn create_registration_token(417 pub async fn create_registration_token(
445 &self,418 &self,
446 created_by: &str,419 created_by: &str,
@@ -470,7 +443,6 @@ impl Store {
470 Ok(token)443 Ok(token)
471 }444 }
472 445
473- /// Whether the registration token with this hash can no longer register a runner: used or gone.
474 pub async fn registration_token_used(&self, token_hash: &str) -> Result<bool> {446 pub async fn registration_token_used(&self, token_hash: &str) -> Result<bool> {
475 let conn = self.inner.conn.lock().await;447 let conn = self.inner.conn.lock().await;
476 let mut rows = conn448 let mut rows = conn
@@ -484,8 +456,6 @@ impl Store {
484 Ok(rows.next().await.map_err(db_err)?.is_none())456 Ok(rows.next().await.map_err(db_err)?.is_none())
485 }457 }
486 458
487- /// Consumes a registration token and creates a runner. Returns the runner and its secret,
488- /// which is shown once. `Invalid` when the token is unknown, used or expired.
489 pub async fn register_runner(459 pub async fn register_runner(
490 &self,460 &self,
491 token_plain: &str,461 token_plain: &str,
@@ -547,8 +517,6 @@ impl Store {
547 Ok((runner, secret))517 Ok((runner, secret))
548 }518 }
549 519
550- /// The runner with this secret, or `None`. Updates its `last_seen_at`. A disabled runner is
551- /// returned with `disabled: true`; the caller decides what to do with it.
552 pub async fn runner_by_secret(&self, secret_plain: &str) -> Result<Option<CiRunner>> {520 pub async fn runner_by_secret(&self, secret_plain: &str) -> Result<Option<CiRunner>> {
553 let hash = hash_token(secret_plain);521 let hash = hash_token(secret_plain);
554 let now = now_stamp();522 let now = now_stamp();
@@ -575,8 +543,6 @@ impl Store {
575 }))543 }))
576 }544 }
577 545
578- /// Stamps the runner's `last_seen_at`. A busy runner does not claim, so its job heartbeats keep
579- /// it from counting as offline.
580 pub async fn touch_runner(&self, id: &str) -> Result<()> {546 pub async fn touch_runner(&self, id: &str) -> Result<()> {
581 let conn = self.inner.conn.lock().await;547 let conn = self.inner.conn.lock().await;
582 conn.execute(548 conn.execute(
@@ -588,7 +554,6 @@ impl Store {
588 Ok(())554 Ok(())
589 }555 }
590 556
591- /// All runners, by name.
592 pub async fn list_runners(&self) -> Result<Vec<CiRunner>> {557 pub async fn list_runners(&self) -> Result<Vec<CiRunner>> {
593 let conn = self.read_conn().await;558 let conn = self.read_conn().await;
594 fetch_all(559 fetch_all(
@@ -600,7 +565,6 @@ impl Store {
600 .await565 .await
601 }566 }
602 567
603- /// Repos the CI scheduler looks at: everything that is not archived.
604 pub async fn repos_for_ci_schedule(&self) -> Result<Vec<crate::Repo>> {568 pub async fn repos_for_ci_schedule(&self) -> Result<Vec<crate::Repo>> {
605 let conn = self.read_conn().await;569 let conn = self.read_conn().await;
606 fetch_all(570 fetch_all(
@@ -616,7 +580,6 @@ impl Store {
616 .await580 .await
617 }581 }
618 582
619- /// When (Unix seconds) the scheduler last checked `repo_id`, if it has.
620 pub async fn ci_schedule_last_tick(&self, repo_id: &str) -> Result<Option<i64>> {583 pub async fn ci_schedule_last_tick(&self, repo_id: &str) -> Result<Option<i64>> {
621 let conn = self.read_conn().await;584 let conn = self.read_conn().await;
622 fetch_opt(585 fetch_opt(
@@ -628,7 +591,6 @@ impl Store {
628 .await591 .await
629 }592 }
630 593
631- /// Records that the scheduler checked `repo_id` at `tick` (Unix seconds).
632 pub async fn set_ci_schedule_last_tick(&self, repo_id: &str, tick: i64) -> Result<()> {594 pub async fn set_ci_schedule_last_tick(&self, repo_id: &str, tick: i64) -> Result<()> {
633 let conn = self.inner.conn.lock().await;595 let conn = self.inner.conn.lock().await;
634 conn.execute(596 conn.execute(
@@ -641,8 +603,6 @@ impl Store {
641 Ok(())603 Ok(())
642 }604 }
643 605
644- /// Forgets `repo_id`, for a repo whose workflow no longer has a schedule. Turning a schedule
645- /// back on later then starts from that moment instead of catching up.
646 pub async fn clear_ci_schedule(&self, repo_id: &str) -> Result<()> {606 pub async fn clear_ci_schedule(&self, repo_id: &str) -> Result<()> {
647 let conn = self.inner.conn.lock().await;607 let conn = self.inner.conn.lock().await;
648 conn.execute(608 conn.execute(
@@ -654,7 +614,6 @@ impl Store {
654 Ok(())614 Ok(())
655 }615 }
656 616
657- /// Disabled runners get no jobs. `NotFound` if the runner does not exist.
658 pub async fn set_runner_disabled(&self, id: &str, disabled: bool) -> Result<()> {617 pub async fn set_runner_disabled(&self, id: &str, disabled: bool) -> Result<()> {
659 let conn = self.inner.conn.lock().await;618 let conn = self.inner.conn.lock().await;
660 let n = conn619 let n = conn
@@ -670,8 +629,6 @@ impl Store {
670 Ok(())629 Ok(())
671 }630 }
672 631
673- /// Sets (`Some`) or clears (`None`) the admin's concurrency override for a runner. The value
674- /// must be 1 to 64, else `Invalid`. `NotFound` if the runner does not exist.
675 pub async fn set_runner_concurrency(&self, id: &str, value: Option<u32>) -> Result<()> {632 pub async fn set_runner_concurrency(&self, id: &str, value: Option<u32>) -> Result<()> {
676 if let Some(n) = value633 if let Some(n) = value
677 && !(MIN_CONCURRENCY..=MAX_CONCURRENCY).contains(&n)634 && !(MIN_CONCURRENCY..=MAX_CONCURRENCY).contains(&n)
@@ -694,11 +651,6 @@ impl Store {
694 Ok(())651 Ok(())
695 }652 }
696 653
697- /// Sets (`Some(text)`) or clears (`None`) the admin override of one runner config field. The
698- /// text is checked by [`validate_runner_field`]; read-only fields and bad values are `Invalid`.
699- /// `concurrency` goes to its own column and `labels` also replaces the labels the runner claims
700- /// with. Clearing `labels` restores the labels the runner reported. `NotFound` if the runner is
701- /// gone.
702 pub async fn set_runner_field(&self, id: &str, key: &str, value: Option<&str>) -> Result<()> {654 pub async fn set_runner_field(&self, id: &str, key: &str, value: Option<&str>) -> Result<()> {
703 let field = crate::ci::runner_field(key)655 let field = crate::ci::runner_field(key)
704 .filter(|f| f.kind != FieldKind::ReadOnly)656 .filter(|f| f.kind != FieldKind::ReadOnly)
@@ -765,8 +717,6 @@ impl Store {
765 Ok(())717 Ok(())
766 }718 }
767 719
768- /// Stores the runner's effective config (secrets already redacted by the runner). Returns true
769- /// when it differs from what was stored.
770 pub async fn set_runner_reported_config(720 pub async fn set_runner_reported_config(
771 &self,721 &self,
772 id: &str,722 id: &str,
@@ -791,7 +741,6 @@ impl Store {
791 Ok(true)741 Ok(true)
792 }742 }
793 743
794- /// Whether the runner is disabled. `false` when the runner is gone. A primary-key read.
795 pub async fn runner_disabled(&self, id: &str) -> Result<bool> {744 pub async fn runner_disabled(&self, id: &str) -> Result<bool> {
796 let conn = self.read_conn().await;745 let conn = self.read_conn().await;
797 let found = fetch_opt(746 let found = fetch_opt(
@@ -804,7 +753,6 @@ impl Store {
804 Ok(found.unwrap_or(false))753 Ok(found.unwrap_or(false))
805 }754 }
806 755
807- /// The runner's concurrency override, read fresh. `None` when unset or the runner is gone.
808 pub async fn runner_concurrency_override(&self, id: &str) -> Result<Option<u32>> {756 pub async fn runner_concurrency_override(&self, id: &str) -> Result<Option<u32>> {
809 let conn = self.read_conn().await;757 let conn = self.read_conn().await;
810 let found = fetch_opt(758 let found = fetch_opt(
@@ -817,8 +765,6 @@ impl Store {
817 Ok(found.flatten())765 Ok(found.flatten())
818 }766 }
819 767
820- /// The text an admin set for a runner field, read fresh. `None` when unset or the runner is
821- /// gone.
822 pub async fn runner_field_override(&self, id: &str, key: &str) -> Result<Option<String>> {768 pub async fn runner_field_override(&self, id: &str, key: &str) -> Result<Option<String>> {
823 let conn = self.read_conn().await;769 let conn = self.read_conn().await;
824 let found = fetch_opt(770 let found = fetch_opt(
@@ -831,8 +777,6 @@ impl Store {
831 Ok(found.and_then(|map| map.get(key).and_then(|v| v.as_str().map(str::to_owned))))777 Ok(found.and_then(|map| map.get(key).and_then(|v| v.as_str().map(str::to_owned))))
832 }778 }
833 779
834- /// Stores what a runner reported about itself. Fields that are `None` keep their stored
835- /// value. Returns true when a stored value changed, so the caller can tell live pages.
836 pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> {780 pub async fn record_runner_report(&self, id: &str, report: &RunnerReport) -> Result<bool> {
837 let conn = self.inner.conn.lock().await;781 let conn = self.inner.conn.lock().await;
838 let Some(current) = load_runner(&conn, id).await? else {782 let Some(current) = load_runner(&conn, id).await? else {
@@ -890,9 +834,6 @@ impl Store {
890 Ok(true)834 Ok(true)
891 }835 }
892 836
893- /// Asks a runner to restart itself. A second request replaces the first, so "drain" can be
894- /// upgraded to "now". `Invalid` when the runner never reported a boot id (too old to obey),
895- /// `NotFound` when it is gone.
896 pub async fn request_runner_restart(&self, id: &str, mode: RestartMode) -> Result<()> {837 pub async fn request_runner_restart(&self, id: &str, mode: RestartMode) -> Result<()> {
897 let conn = self.inner.conn.lock().await;838 let conn = self.inner.conn.lock().await;
898 let runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?;839 let runner = load_runner(&conn, id).await?.ok_or(Error::NotFound)?;
@@ -910,7 +851,6 @@ impl Store {
910 Ok(())851 Ok(())
911 }852 }
912 853
913- /// The restart pending for a runner, read fresh. `None` when none or the runner is gone.
914 pub async fn runner_restart(&self, id: &str) -> Result<Option<RestartMode>> {854 pub async fn runner_restart(&self, id: &str) -> Result<Option<RestartMode>> {
915 let conn = self.read_conn().await;855 let conn = self.read_conn().await;
916 let found = fetch_opt(856 let found = fetch_opt(
@@ -923,7 +863,6 @@ impl Store {
923 Ok(found.flatten().and_then(|m| RestartMode::parse(&m)))863 Ok(found.flatten().and_then(|m| RestartMode::parse(&m)))
924 }864 }
925 865
926- /// Removes a runner. `NotFound` if it does not exist.
927 pub async fn delete_runner(&self, id: &str) -> Result<()> {866 pub async fn delete_runner(&self, id: &str) -> Result<()> {
928 let conn = self.inner.conn.lock().await;867 let conn = self.inner.conn.lock().await;
929 let n = conn868 let n = conn
@@ -936,12 +875,6 @@ impl Store {
936 Ok(())875 Ok(())
937 }876 }
938 877
939- /// Creates a run with the next number for the repo, and its jobs, in one transaction.
940- ///
941- /// Initial states: a config error gives an `Error` run with no jobs. A run with no jobs
942- /// succeeds at once. With `needs_approval` the run waits and its need-less jobs are
943- /// `Blocked` until `approve_run`. Otherwise need-less jobs are `Queued` and the run is
944- /// `Queued`. Jobs with needs are always `Blocked` at first.
945 #[allow(clippy::too_many_arguments)]878 #[allow(clippy::too_many_arguments)]
946 pub async fn create_run(&self, run: &NewRun<'_>, jobs: &[NewJob<'_>]) -> Result<CiRun> {879 pub async fn create_run(&self, run: &NewRun<'_>, jobs: &[NewJob<'_>]) -> Result<CiRun> {
947 let NewRun {880 let NewRun {
@@ -1028,8 +961,6 @@ impl Store {
1028 finish(tx, outcome).await961 finish(tx, outcome).await
1029 }962 }
1030 963
1031- /// `WaitingApproval` -> `Queued`. Need-less jobs become `Queued`. `Conflict` when the run is
1032- /// not waiting for approval.
1033 pub async fn approve_run(&self, run_id: &str) -> Result<()> {964 pub async fn approve_run(&self, run_id: &str) -> Result<()> {
1034 let now = now_stamp();965 let now = now_stamp();
1035 let conn = self.inner.conn.lock().await;966 let conn = self.inner.conn.lock().await;
@@ -1053,16 +984,10 @@ impl Store {
1053 finish(tx, outcome).await984 finish(tx, outcome).await
1054 }985 }
1055 986
1056- /// Claims the oldest queued job whose `runs_on` the runner's labels cover. The claim is an
1057- /// UPDATE guarded by `state = 'queued'`, so only one claimer can win a job. Returns the job,
1058- /// its run and the plaintext job token, which is shown once. A disabled runner gets nothing.
1059 pub async fn claim_job(&self, runner: &CiRunner) -> Result<Option<(CiJob, CiRun, String)>> {987 pub async fn claim_job(&self, runner: &CiRunner) -> Result<Option<(CiJob, CiRun, String)>> {
1060 self.claim_job_fitting(runner, None).await988 self.claim_job_fitting(runner, None).await
1061 }989 }
1062 990
1063- /// Like [`Store::claim_job`], and when `offer` is set only claims a job whose memory
1064- /// reservation fits the runner's free memory, see [`pick_by_memory`]. Without an offer, which
1065- /// is an older runner, the oldest compatible job is taken.
1066 pub async fn claim_job_fitting(991 pub async fn claim_job_fitting(
1067 &self,992 &self,
1068 runner: &CiRunner,993 runner: &CiRunner,
@@ -1139,8 +1064,6 @@ impl Store {
1139 Ok(claimed.map(|(job, run)| (job, run, token)))1064 Ok(claimed.map(|(job, run)| (job, run, token)))
1140 }1065 }
1141 1066
1142- /// Counts the queued jobs that `runner` with `offer` cannot take, and why. Read only: it
1143- /// claims nothing, so it is safe to call for a note on a claim that got no job.
1144 pub async fn queue_skips(1067 pub async fn queue_skips(
1145 &self,1068 &self,
1146 runner: &CiRunner,1069 runner: &CiRunner,
@@ -1193,7 +1116,6 @@ impl Store {
1193 Ok(skips)1116 Ok(skips)
1194 }1117 }
1195 1118
1196- /// The job, only while it is running and the token matches its stored hash.
1197 pub async fn job_by_token(&self, job_id: &str, token_plain: &str) -> Result<Option<CiJob>> {1119 pub async fn job_by_token(&self, job_id: &str, token_plain: &str) -> Result<Option<CiJob>> {
1198 let conn = self.read_conn().await;1120 let conn = self.read_conn().await;
1199 fetch_opt(1121 fetch_opt(
@@ -1208,8 +1130,6 @@ impl Store {
1208 .await1130 .await
1209 }1131 }
1210 1132
1211- /// Stamps the job's heartbeat and returns whether a cancel was requested. `NotFound` when
1212- /// the job is not running any more, so the runner stops.
1213 pub async fn heartbeat(&self, job_id: &str) -> Result<bool> {1133 pub async fn heartbeat(&self, job_id: &str) -> Result<bool> {
1214 let now = now_stamp();1134 let now = now_stamp();
1215 let conn = self.inner.conn.lock().await;1135 let conn = self.inner.conn.lock().await;
@@ -1233,7 +1153,6 @@ impl Store {
1233 .ok_or(Error::NotFound)1153 .ok_or(Error::NotFound)
1234 }1154 }
1235 1155
1236- /// Records the OOM kills a runner saw in the job's cgroup. Zero is stored as nothing.
1237 pub async fn set_job_oom_kills(&self, job_id: &str, kills: u32) -> Result<()> {1156 pub async fn set_job_oom_kills(&self, job_id: &str, kills: u32) -> Result<()> {
1238 if kills == 0 {1157 if kills == 0 {
1239 return Ok(());1158 return Ok(());
@@ -1248,7 +1167,6 @@ impl Store {
1248 Ok(())1167 Ok(())
1249 }1168 }
1250 1169
1251- /// Adds to the job's log size.
1252 pub async fn add_log_bytes(&self, job_id: &str, n: i64) -> Result<()> {1170 pub async fn add_log_bytes(&self, job_id: &str, n: i64) -> Result<()> {
1253 if n < 0 {1171 if n < 0 {
1254 return Err(Error::Invalid("log bytes cannot go down".into()));1172 return Err(Error::Invalid("log bytes cannot go down".into()));
@@ -1267,10 +1185,6 @@ impl Store {
1267 Ok(())1185 Ok(())
1268 }1186 }
1269 1187
1270- /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the
1271- /// run state is recomputed. A `Failure` or `Error` fails the run fast: the run's queued and
1272- /// blocked jobs are cancelled and its running jobs get `cancel_requested`. Returns the run.
1273- /// `Conflict` if the job already finished.
1274 pub async fn finish_job(1188 pub async fn finish_job(
1275 &self,1189 &self,
1276 job_id: &str,1190 job_id: &str,
@@ -1315,9 +1229,6 @@ impl Store {
1315 finish(tx, outcome).await1229 finish(tx, outcome).await
1316 }1230 }
1317 1231
1318- /// Hands a running job back to the queue. The original `queued_at` is kept, so the job keeps
1319- /// its priority and its anti-starvation clock. The runner, token, timestamps, log size and
1320- /// OOM count of the attempt are cleared. Returns false when the job is not running.
1321 pub async fn requeue_job(&self, job_id: &str) -> Result<bool> {1232 pub async fn requeue_job(&self, job_id: &str) -> Result<bool> {
1322 let now = now_stamp();1233 let now = now_stamp();
1323 let conn = self.inner.conn.lock().await;1234 let conn = self.inner.conn.lock().await;
@@ -1353,8 +1264,6 @@ impl Store {
1353 finish(tx, outcome).await1264 finish(tx, outcome).await
1354 }1265 }
1355 1266
1356- /// Cancels the run's queued and blocked jobs now, and sets `cancel_requested` on its running
1357- /// jobs. Does nothing to a run that already finished.
1358 pub async fn request_cancel(&self, run_id: &str) -> Result<()> {1267 pub async fn request_cancel(&self, run_id: &str) -> Result<()> {
1359 let now = now_stamp();1268 let now = now_stamp();
1360 let conn = self.inner.conn.lock().await;1269 let conn = self.inner.conn.lock().await;
@@ -1371,18 +1280,12 @@ impl Store {
1371 finish(tx, outcome).await1280 finish(tx, outcome).await
1372 }1281 }
1373 1282
1374- /// A new run, with the next number, for the same commit, ref, trigger and job specs. The
1375- /// new run is queued at once, without approval.
1376 pub async fn rerun(&self, run_id: &str, actor_id: &str) -> Result<CiRun> {1283 pub async fn rerun(&self, run_id: &str, actor_id: &str) -> Result<CiRun> {
1377 let (run, jobs) = self.run_and_jobs(run_id).await?;1284 let (run, jobs) = self.run_and_jobs(run_id).await?;
1378 let names: Vec<String> = jobs.iter().map(|j| j.name.clone()).collect();1285 let names: Vec<String> = jobs.iter().map(|j| j.name.clone()).collect();
1379 self.rerun_subset(&run, &jobs, &names, actor_id).await1286 self.rerun_subset(&run, &jobs, &names, actor_id).await
1380 }1287 }
1381 1288
1382- /// A new run with only the failed, errored and cancelled jobs of a finished run, and every
1383- /// job that depends on them (directly or not). Specs are the originals; a need on a job that
1384- /// is not in the new run is dropped, since that job succeeded in the original run.
1385- /// `Conflict` when the run is not finished or has no such job.
1386 pub async fn rerun_failed(&self, run_id: &str, actor_id: &str) -> Result<CiRun> {1289 pub async fn rerun_failed(&self, run_id: &str, actor_id: &str) -> Result<CiRun> {
1387 let (run, jobs) = self.run_and_jobs(run_id).await?;1290 let (run, jobs) = self.run_and_jobs(run_id).await?;
1388 if !run.state.is_terminal() {1291 if !run.state.is_terminal() {
@@ -1404,8 +1307,6 @@ impl Store {
1404 self.rerun_subset(&run, &jobs, &seeds, actor_id).await1307 self.rerun_subset(&run, &jobs, &seeds, actor_id).await
1405 }1308 }
1406 1309
1407- /// A new run with one finished job of `run_id` and the jobs that depend on it. `NotFound` when
1408- /// the job is not in the run, `Conflict` when it has not finished.
1409 pub async fn rerun_job(&self, run_id: &str, job_id: &str, actor_id: &str) -> Result<CiRun> {1310 pub async fn rerun_job(&self, run_id: &str, job_id: &str, actor_id: &str) -> Result<CiRun> {
1410 let (run, jobs) = self.run_and_jobs(run_id).await?;1311 let (run, jobs) = self.run_and_jobs(run_id).await?;
1411 let job = jobs1312 let job = jobs
@@ -1426,7 +1327,6 @@ impl Store {
1426 Ok((run, jobs))1327 Ok((run, jobs))
1427 }1328 }
1428 1329
1429- /// Creates a run of `seeds` and their dependants out of `jobs`, and copies the warnings.
1430 async fn rerun_subset(1330 async fn rerun_subset(
1431 &self,1331 &self,
1432 run: &CiRun,1332 run: &CiRun,
@@ -1491,7 +1391,6 @@ impl Store {
1491 Ok(created)1391 Ok(created)
1492 }1392 }
1493 1393
1494- /// Stores the config warnings of a run, replacing any earlier ones.
1495 pub async fn set_run_warnings(&self, run_id: &str, warnings: &[String]) -> Result<()> {1394 pub async fn set_run_warnings(&self, run_id: &str, warnings: &[String]) -> Result<()> {
1496 let lines: Vec<String> = warnings1395 let lines: Vec<String> = warnings
1497 .iter()1396 .iter()
@@ -1508,7 +1407,6 @@ impl Store {
1508 Ok(())1407 Ok(())
1509 }1408 }
1510 1409
1511- /// The config warnings stored for a run, in order.
1512 pub async fn run_warnings(&self, run_id: &str) -> Result<Vec<String>> {1410 pub async fn run_warnings(&self, run_id: &str) -> Result<Vec<String>> {
1513 let conn = self.read_conn().await;1411 let conn = self.read_conn().await;
1514 let joined = fetch_opt(1412 let joined = fetch_opt(
@@ -1524,8 +1422,6 @@ impl Store {
1524 .unwrap_or_default())1422 .unwrap_or_default())
1525 }1423 }
1526 1424
1527- /// Runs on `git_ref` of the repo that are still queued or running, were started by a push, and
1528- /// are for a commit other than `commit_oid`. The runs a newer push supersedes.
1529 pub async fn superseded_candidates(1425 pub async fn superseded_candidates(
1530 &self,1426 &self,
1531 repo_id: &str,1427 repo_id: &str,
@@ -1550,9 +1446,6 @@ impl Store {
1550 .await1446 .await
1551 }1447 }
1552 1448
1553- /// Running jobs whose heartbeat is older than `older_than` become `Error` with the message
1554- /// "runner lost". Their dependants and run are updated as in `finish_job`. Returns the
1555- /// reaped jobs.
1556 pub async fn reap_lost_jobs(&self, older_than: &str) -> Result<Vec<CiJob>> {1449 pub async fn reap_lost_jobs(&self, older_than: &str) -> Result<Vec<CiJob>> {
1557 let now = now_stamp();1450 let now = now_stamp();
1558 let conn = self.inner.conn.lock().await;1451 let conn = self.inner.conn.lock().await;
@@ -1621,8 +1514,6 @@ impl Store {
1621 load_run(&conn, id).await1514 load_run(&conn, id).await
1622 }1515 }
1623 1516
1624- /// The newest run of a repo on a full ref name such as `refs/heads/main`. Newest is the
1625- /// highest run number, which is assigned at creation.
1626 pub async fn latest_run_on_ref(&self, repo_id: &str, git_ref: &str) -> Result<Option<CiRun>> {1517 pub async fn latest_run_on_ref(&self, repo_id: &str, git_ref: &str) -> Result<Option<CiRun>> {
1627 let conn = self.read_conn().await;1518 let conn = self.read_conn().await;
1628 fetch_opt(1519 fetch_opt(
@@ -1637,8 +1528,6 @@ impl Store {
1637 .await1528 .await
1638 }1529 }
1639 1530
1640- /// One page of a repo's runs, newest first, and the total count. `page` starts at 1 and
1641- /// `per_page` is capped at 100.
1642 pub async fn list_runs(1531 pub async fn list_runs(
1643 &self,1532 &self,
1644 repo_id: &str,1533 repo_id: &str,
@@ -1671,15 +1560,11 @@ impl Store {
1671 Ok((runs, total))1560 Ok((runs, total))
1672 }1561 }
1673 1562
1674- /// The jobs of a run, in insertion order: dependency order, matrix combinations grouped.
1675 pub async fn jobs_for_run(&self, run_id: &str) -> Result<Vec<CiJob>> {1563 pub async fn jobs_for_run(&self, run_id: &str) -> Result<Vec<CiJob>> {
1676 let conn = self.read_conn().await;1564 let conn = self.read_conn().await;
1677 jobs_of_run(&conn, run_id).await1565 jobs_of_run(&conn, run_id).await
1678 }1566 }
1679 1567
1680- /// The durations of finished jobs that the CI time estimate learns from: each successful run's
1681- /// jobs for the newest five successful runs of each branch in `git_refs`, and for the newest five
1682- /// successful runs on any branch. One query, bounded by the refs given.
1683 pub async fn recent_job_samples(1568 pub async fn recent_job_samples(
1684 &self,1569 &self,
1685 repo_id: &str,1570 repo_id: &str,
@@ -1712,8 +1597,6 @@ impl Store {
1712 Ok(rows.into_iter().flatten().collect())1597 Ok(rows.into_iter().flatten().collect())
1713 }1598 }
1714 1599
1715- /// How far a job's log has been scanned for steps, and how many groups are open there.
1716- /// `NotFound` if the job does not exist.
1717 pub async fn step_scan(&self, job_id: &str) -> Result<(u64, u32)> {1600 pub async fn step_scan(&self, job_id: &str) -> Result<(u64, u32)> {
1718 let conn = self.read_conn().await;1601 let conn = self.read_conn().await;
1719 let row = fetch_opt(1602 let row = fetch_opt(
@@ -1730,8 +1613,6 @@ impl Store {
1730 ))1613 ))
1731 }1614 }
1732 1615
1733- /// Stores the marks of one log scan and the new scan position. A start is kept while the job
1734- /// has fewer than `MAX_STEPS` steps. An end closes the newest open step, if any.
1735 pub async fn apply_step_scan(1616 pub async fn apply_step_scan(
1736 &self,1617 &self,
1737 job_id: &str,1618 job_id: &str,
@@ -1798,7 +1679,6 @@ impl Store {
1798 finish(tx, outcome).await1679 finish(tx, outcome).await
1799 }1680 }
1800 1681
1801- /// Every step of a run's jobs, ordered by job, then by step.
1802 pub async fn steps_for_run(&self, run_id: &str) -> Result<Vec<JobStep>> {1682 pub async fn steps_for_run(&self, run_id: &str) -> Result<Vec<JobStep>> {
1803 let conn = self.read_conn().await;1683 let conn = self.read_conn().await;
1804 fetch_all(1684 fetch_all(
@@ -1821,8 +1701,6 @@ impl Store {
1821 .await1701 .await
1822 }1702 }
1823 1703
1824- /// One step's duration in the recent successful runs of a repo, sampled as `recent_job_samples`
1825- /// samples jobs. Only finished steps of successful jobs count.
1826 pub async fn recent_step_samples(1704 pub async fn recent_step_samples(
1827 &self,1705 &self,
1828 repo_id: &str,1706 repo_id: &str,
@@ -1857,8 +1735,6 @@ impl Store {
1857 Ok(rows.into_iter().flatten().collect())1735 Ok(rows.into_iter().flatten().collect())
1858 }1736 }
1859 1737
1860- /// The jobs a runner holds or held: every running one, then its `recent` newest finished jobs
1861- /// (by start time). Each carries its run's number and its repo's owner and name.
1862 pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result<Vec<RunnerJob>> {1738 pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result<Vec<RunnerJob>> {
1863 let conn = self.read_conn().await;1739 let conn = self.read_conn().await;
1864 let mut jobs = fetch_all(1740 let mut jobs = fetch_all(
@@ -1895,7 +1771,6 @@ impl Store {
1895 load_job(&conn, id).await1771 load_job(&conn, id).await
1896 }1772 }
1897 1773
1898- /// Records an artifact of a job. `Conflict` if the job already has one with this name.
1899 pub async fn add_artifact(1774 pub async fn add_artifact(
1900 &self,1775 &self,
1901 job_id: &str,1776 job_id: &str,
@@ -1932,7 +1807,6 @@ impl Store {
1932 Ok(artifact)1807 Ok(artifact)
1933 }1808 }
1934 1809
1935- /// The artifacts of a job, by name.
1936 pub async fn list_artifacts(&self, job_id: &str) -> Result<Vec<CiArtifact>> {1810 pub async fn list_artifacts(&self, job_id: &str) -> Result<Vec<CiArtifact>> {
1937 let conn = self.read_conn().await;1811 let conn = self.read_conn().await;
1938 fetch_all(1812 fetch_all(
@@ -1944,7 +1818,6 @@ impl Store {
1944 .await1818 .await
1945 }1819 }
1946 1820
1947- /// One artifact of a job, by name.
1948 pub async fn artifact(&self, job_id: &str, name: &str) -> Result<Option<CiArtifact>> {1821 pub async fn artifact(&self, job_id: &str, name: &str) -> Result<Option<CiArtifact>> {
1949 let conn = self.read_conn().await;1822 let conn = self.read_conn().await;
1950 fetch_opt(1823 fetch_opt(
@@ -1956,14 +1829,6 @@ impl Store {
1956 .await1829 .await
1957 }1830 }
1958 1831
1959- /// Retention. Jobs of runs that finished before `logs_before` and still have logs get
1960- /// `log_bytes = 0`; their ids are returned so the caller deletes the log files. Artifact rows
1961- /// created before `artifacts_before` are deleted. Then, per repo, the artifacts of every run
1962- /// but the newest `keep_runs` runs that have artifacts are deleted (0 keeps all). Then, if
1963- /// `max_total_bytes` is non-zero and the artifacts left still exceed it, the artifacts of the
1964- /// oldest runs are deleted a whole run at a time until the total fits. Artifact ids are
1965- /// returned (deduplicated) so the caller deletes the files. Run ids are returned too (the runs
1966- /// whose logs or artifacts went), so the pages showing them can be woken.
1967 pub async fn purge_old(1832 pub async fn purge_old(
1968 &self,1833 &self,
1969 logs_before: &str,1834 logs_before: &str,
@@ -2080,8 +1945,6 @@ impl Store {
2080 finish(tx, outcome).await1945 finish(tx, outcome).await
2081 }1946 }
2082 1947
2083- /// Stores or replaces a repo secret. Sealed with the instance key. The name must match the
2084- /// JobSpec secret rule, and the value must be UTF-8.
2085 pub async fn set_ci_secret(&self, repo_id: &str, name: &str, value: &[u8]) -> Result<()> {1948 pub async fn set_ci_secret(&self, repo_id: &str, name: &str, value: &[u8]) -> Result<()> {
2086 validate_secret_name(name)?;1949 validate_secret_name(name)?;
2087 std::str::from_utf8(value)1950 std::str::from_utf8(value)
@@ -2107,7 +1970,6 @@ impl Store {
2107 Ok(())1970 Ok(())
2108 }1971 }
2109 1972
2110- /// Deletes a repo secret. Returns whether one existed.
2111 pub async fn delete_ci_secret(&self, repo_id: &str, name: &str) -> Result<bool> {1973 pub async fn delete_ci_secret(&self, repo_id: &str, name: &str) -> Result<bool> {
2112 let conn = self.inner.conn.lock().await;1974 let conn = self.inner.conn.lock().await;
2113 let n = conn1975 let n = conn
@@ -2120,7 +1982,6 @@ impl Store {
2120 Ok(n > 0)1982 Ok(n > 0)
2121 }1983 }
2122 1984
2123- /// Secret names and their `updated_at`, by name. Values are never read.
2124 pub async fn list_ci_secret_names(&self, repo_id: &str) -> Result<Vec<(String, String)>> {1985 pub async fn list_ci_secret_names(&self, repo_id: &str) -> Result<Vec<(String, String)>> {
2125 let conn = self.read_conn().await;1986 let conn = self.read_conn().await;
2126 fetch_all(1987 fetch_all(
@@ -2132,8 +1993,6 @@ impl Store {
2132 .await1993 .await
2133 }1994 }
2134 1995
2135- /// Opened values of the named secrets. Names that do not exist are omitted. For the claim
2136- /// path only.
2137 pub async fn ci_secret_values(1996 pub async fn ci_secret_values(
2138 &self,1997 &self,
2139 repo_id: &str,1998 repo_id: &str,
@@ -2840,8 +2699,6 @@ mod tests {
2840 ));2699 ));
2841 }2700 }
2842 2701
2843- /// Like `create`, then gives the jobs distinct, increasing `queued_at` in the order listed,
2844- /// because jobs created together tie and then sort by random id.
2845 async fn create_ordered(2702 async fn create_ordered(
2846 store: &Store,2703 store: &Store,
2847 repo_id: &str,2704 repo_id: &str,
@@ -3778,7 +3635,6 @@ mod tests {
3778 .unwrap()3635 .unwrap()
3779 }3636 }
3780 3637
3781- /// Each scenario works in its own repo and leaves its jobs unclaimed, so they share one store.
3782 #[tokio::test]3638 #[tokio::test]
3783 async fn repo_scenarios_share_one_store() {3639 async fn repo_scenarios_share_one_store() {
3784 let fx = fixture().await;3640 let fx = fixture().await;
crates/forge-core/src/store/commit_status.rsmodified+0 -32
@@ -1,7 +1,3 @@
1-//! Commit statuses: one row per (repo, commit, context). Posting again for the same context
2-//! replaces the row, so the latest report wins. `combined_state` folds the rows of one commit
3-//! into the single state shown next to it.
4-
5 use std::collections::HashMap;1 use std::collections::HashMap;
6 2
7 use turso::{Row, Value};3 use turso::{Row, Value};
@@ -10,19 +6,14 @@ use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, missing
10 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
11 use crate::time::now_stamp;7 use crate::time::now_stamp;
12 8
13-/// Longest accepted context name, in characters.
14 pub const MAX_CONTEXT_CHARS: usize = 255;9 pub const MAX_CONTEXT_CHARS: usize = 255;
15-/// Longest accepted description, in characters.
16 pub const MAX_DESCRIPTION_CHARS: usize = 1024;10 pub const MAX_DESCRIPTION_CHARS: usize = 1024;
17-/// Longest accepted target URL, in bytes.
18 pub const MAX_TARGET_URL_BYTES: usize = 2048;11 pub const MAX_TARGET_URL_BYTES: usize = 2048;
19-/// Context used when a report does not name one.
20 pub const DEFAULT_CONTEXT: &str = "default";12 pub const DEFAULT_CONTEXT: &str = "default";
21 13
22 const STATUS_COLS: &str = "id, repo_id, sha, context, state, description, target_url, creator_id, \14 const STATUS_COLS: &str = "id, repo_id, sha, context, state, description, target_url, creator_id, \
23 created_at, updated_at";15 created_at, updated_at";
24 16
25-/// The state a commit status reports.
26 #[derive(Debug, Clone, Copy, PartialEq, Eq)]17 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
27 pub enum StatusState {18 pub enum StatusState {
28 Pending,19 Pending,
@@ -52,7 +43,6 @@ impl StatusState {
52 }43 }
53 }44 }
54 45
55-/// One status row as stored.
56 #[derive(Debug, Clone, PartialEq, Eq)]46 #[derive(Debug, Clone, PartialEq, Eq)]
57 pub struct CommitStatus {47 pub struct CommitStatus {
58 pub id: String,48 pub id: String,
@@ -67,8 +57,6 @@ pub struct CommitStatus {
67 pub updated_at: String,57 pub updated_at: String,
68 }58 }
69 59
70-/// Folds the states of one commit's statuses. Any failure or error makes the result failure, else
71-/// any pending makes it pending, else success. `None` when there are no statuses.
72 pub fn combine<I>(states: I) -> Option<StatusState>60 pub fn combine<I>(states: I) -> Option<StatusState>
73 where61 where
74 I: IntoIterator<Item = StatusState>,62 I: IntoIterator<Item = StatusState>,
@@ -90,7 +78,6 @@ where
90 }78 }
91 }79 }
92 80
93-/// True for a full object id: 40 (SHA-1) or 64 (SHA-256) lowercase hex characters.
94 pub fn is_full_sha(sha: &str) -> bool {81 pub fn is_full_sha(sha: &str) -> bool {
95 matches!(sha.len(), 40 | 64) && sha.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))82 matches!(sha.len(), 40 | 64) && sha.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
96 }83 }
@@ -153,9 +140,6 @@ fn opt_value(text: Option<String>) -> Value {
153 }140 }
154 141
155 impl Store {142 impl Store {
156- /// Records `state` for `context` on the commit. An existing row for the same context is
157- /// replaced, including its creator and description. The commit itself is not checked here;
158- /// callers verify that it exists in the repo.
159 #[allow(clippy::too_many_arguments)]143 #[allow(clippy::too_many_arguments)]
160 pub async fn set_status(144 pub async fn set_status(
161 &self,145 &self,
@@ -215,7 +199,6 @@ impl Store {
215 .ok_or_else(missing_row)199 .ok_or_else(missing_row)
216 }200 }
217 201
218- /// Every status of one commit, ordered by context.
219 pub async fn statuses_for(&self, repo_id: &str, sha: &str) -> Result<Vec<CommitStatus>> {202 pub async fn statuses_for(&self, repo_id: &str, sha: &str) -> Result<Vec<CommitStatus>> {
220 let conn = self.read_conn().await;203 let conn = self.read_conn().await;
221 fetch_all(204 fetch_all(
@@ -230,8 +213,6 @@ impl Store {
230 .await213 .await
231 }214 }
232 215
233- /// Distinct status contexts seen in the repo, most recently reported first. Feeds the
234- /// required-checks picker in branch protection.
235 pub async fn recent_status_contexts(&self, repo_id: &str, limit: u32) -> Result<Vec<String>> {216 pub async fn recent_status_contexts(&self, repo_id: &str, limit: u32) -> Result<Vec<String>> {
236 let conn = self.read_conn().await;217 let conn = self.read_conn().await;
237 fetch_all(218 fetch_all(
@@ -244,14 +225,11 @@ impl Store {
244 .await225 .await
245 }226 }
246 227
247- /// The combined state of one commit, or `None` when it has no statuses.
248 pub async fn combined_state(&self, repo_id: &str, sha: &str) -> Result<Option<StatusState>> {228 pub async fn combined_state(&self, repo_id: &str, sha: &str) -> Result<Option<StatusState>> {
249 let statuses = self.statuses_for(repo_id, sha).await?;229 let statuses = self.statuses_for(repo_id, sha).await?;
250 Ok(combine(statuses.into_iter().map(|s| s.state)))230 Ok(combine(statuses.into_iter().map(|s| s.state)))
251 }231 }
252 232
253- /// Combined state for each of `shas` that has at least one status, in one query. Commits
254- /// without statuses are absent from the map.
255 pub async fn statuses_for_many(233 pub async fn statuses_for_many(
256 &self,234 &self,
257 repo_id: &str,235 repo_id: &str,
@@ -266,8 +244,6 @@ impl Store {
266 .collect())244 .collect())
267 }245 }
268 246
269- /// Every status row of each of `shas`, grouped by commit, in one query. Commits without
270- /// statuses are absent from the map. Used by the commit list to show each context.
271 pub async fn statuses_for_many_rows(247 pub async fn statuses_for_many_rows(
272 &self,248 &self,
273 repo_id: &str,249 repo_id: &str,
@@ -378,8 +354,6 @@ mod tests {
378 (dir, store, repo.id, owner.id)354 (dir, store, repo.id, owner.id)
379 }355 }
380 356
381- // One store and owner serve every scenario. Each scenario that writes
382- // statuses gets its own repo so the scenarios cannot see each other.
383 async fn new_repo(store: &Store, owner_id: &str, name: &str) -> String {357 async fn new_repo(store: &Store, owner_id: &str, name: &str) -> String {
384 store358 store
385 .create_repo(owner_id, name, "", Visibility::Public, "main")359 .create_repo(owner_id, name, "", Visibility::Public, "main")
@@ -392,7 +366,6 @@ mod tests {
392 async fn status_scenarios_share_one_store() {366 async fn status_scenarios_share_one_store() {
393 let (_dir, store, repo_id, user_id) = fixture().await;367 let (_dir, store, repo_id, user_id) = fixture().await;
394 368
395- // Upsert: one row per context, the latest report wins, states combine.
396 let set = |context: &'static str, state: StatusState| {369 let set = |context: &'static str, state: StatusState| {
397 let store = store.clone();370 let store = store.clone();
398 let repo_id = repo_id.clone();371 let repo_id = repo_id.clone();
@@ -419,7 +392,6 @@ mod tests {
419 "upsert: failure wins over success"392 "upsert: failure wins over success"
420 );393 );
421 394
422- // The latest report for "a" replaces the failure.
423 let replaced = set("a", StatusState::Success).await;395 let replaced = set("a", StatusState::Success).await;
424 assert_eq!(replaced.state, StatusState::Success, "upsert: stored state");396 assert_eq!(replaced.state, StatusState::Success, "upsert: stored state");
425 assert_eq!(397 assert_eq!(
@@ -439,7 +411,6 @@ mod tests {
439 "upsert: unreported commit has no state"411 "upsert: unreported commit has no state"
440 );412 );
441 413
442- // Many-lookup skips commits without statuses.
443 let many_repo = new_repo(&store, &user_id, "many").await;414 let many_repo = new_repo(&store, &user_id, "many").await;
444 store415 store
445 .set_status(416 .set_status(
@@ -472,7 +443,6 @@ mod tests {
472 "many: empty input gives nothing"443 "many: empty input gives nothing"
473 );444 );
474 445
475- // Invalid input is refused and stores nothing.
476 let invalid_repo = new_repo(&store, &user_id, "invalid").await;446 let invalid_repo = new_repo(&store, &user_id, "invalid").await;
477 let bad_sha = store447 let bad_sha = store
478 .set_status(448 .set_status(
@@ -513,7 +483,6 @@ mod tests {
513 "invalid: nothing stored"483 "invalid: nothing stored"
514 );484 );
515 485
516- // Deleting the repo removes its statuses.
517 let doomed_repo = new_repo(&store, &user_id, "doomed").await;486 let doomed_repo = new_repo(&store, &user_id, "doomed").await;
518 store487 store
519 .set_status(488 .set_status(
@@ -537,7 +506,6 @@ mod tests {
537 "delete repo: statuses gone"506 "delete repo: statuses gone"
538 );507 );
539 508
540- // Deleting a user reassigns their statuses to the ghost user.
541 let reassigned_repo = new_repo(&store, &user_id, "reassigned").await;509 let reassigned_repo = new_repo(&store, &user_id, "reassigned").await;
542 let reporter = store510 let reporter = store
543 .create_user("ci-bot", None, "not-a-real-hash", false)511 .create_user("ci-bot", None, "not-a-real-hash", false)
crates/forge-core/src/store/contributions.rsmodified+0 -27
@@ -1,5 +1,3 @@
1-//! Daily contribution counts for one user, for the dashboard heatmap.
2-
3 use std::collections::BTreeMap;1 use std::collections::BTreeMap;
4 2
5 use jiff::Timestamp;3 use jiff::Timestamp;
@@ -10,7 +8,6 @@ use super::{Store, col_int, col_text, db_err, fetch_all, new_id};
10 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
11 use crate::tz::local_date;9 use crate::tz::local_date;
12 10
13-/// Most contributions `contributions_between` returns for one day.
14 const DAY_LIMIT: u32 = 200;11 const DAY_LIMIT: u32 = 200;
15 12
16 fn activity_sql() -> String {13 fn activity_sql() -> String {
@@ -34,8 +31,6 @@ fn activity_sql() -> String {
34 )31 )
35 }32 }
36 33
37-/// What a contribution was: a branch push, an issue, pull request or comment the user wrote, or
38-/// a commit the user was credited with as a co-author.
39 #[derive(Clone, Copy, Debug, PartialEq, Eq)]34 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
40 pub enum ContributionKind {35 pub enum ContributionKind {
41 Push,36 Push,
@@ -45,21 +40,15 @@ pub enum ContributionKind {
45 CoAuthored,40 CoAuthored,
46 }41 }
47 42
48-/// One contribution, with the repo it landed in.
49 #[derive(Clone, Debug, PartialEq, Eq)]43 #[derive(Clone, Debug, PartialEq, Eq)]
50 pub struct ContributionItem {44 pub struct ContributionItem {
51 pub kind: ContributionKind,45 pub kind: ContributionKind,
52 pub repo_owner: String,46 pub repo_owner: String,
53 pub repo_name: String,47 pub repo_name: String,
54- /// When it happened, as an RFC 3339 UTC stamp.
55 pub created_at: String,48 pub created_at: String,
56- /// The pushed ref such as `refs/heads/main`; empty for everything else.
57 pub ref_name: String,49 pub ref_name: String,
58- /// The issue or pull request number (a comment's is its issue's); 0 for a push.
59 pub number: i64,50 pub number: i64,
60- /// The issue or pull request title, or a co-authored commit's summary; empty for a push.
61 pub title: String,51 pub title: String,
62- /// The co-authored commit's object id; empty for everything else.
63 pub commit: String,52 pub commit: String,
64 }53 }
65 54
@@ -89,13 +78,6 @@ fn map_item(row: &Row) -> Result<ContributionItem> {
89 }78 }
90 79
91 impl Store {80 impl Store {
92- /// Contributions per day in `tz` by `user_id` at or after `since` (an RFC 3339 stamp), as
93- /// `(YYYY-MM-DD, count)` sorted by day ascending; days with no activity are left out.
94- /// Events are grouped by minute and each minute is placed on its local day, so zones with
95- /// half-hour or quarter-hour offsets and DST changes land on the right day.
96- /// A contribution is a push (ref deletions are left out), an issue or pull request opened
97- /// (pull requests are `issues` rows with `kind = 'pull'`), or a comment. Only public repos count:
98- /// a repo made private takes its contributions off the calendar.
99 pub async fn contribution_counts(81 pub async fn contribution_counts(
100 &self,82 &self,
101 user_id: &str,83 user_id: &str,
@@ -130,8 +112,6 @@ impl Store {
130 Ok(days.into_iter().collect())112 Ok(days.into_iter().collect())
131 }113 }
132 114
133- /// The contributions by `user_id` with a stamp in `[from, to)`, both RFC 3339 stamps, newest
134- /// first and at most `DAY_LIMIT` of them. The same kinds as `contribution_counts` count.
135 pub async fn contributions_between(115 pub async fn contributions_between(
136 &self,116 &self,
137 user_id: &str,117 user_id: &str,
@@ -157,9 +137,6 @@ impl Store {
157 fetch_all(&conn, &sql, params, map_item).await137 fetch_all(&conn, &sql, params, map_item).await
158 }138 }
159 139
160- /// Credits `user_id` with a co-authored commit in `repo_id`. A commit is recorded once per
161- /// user and repo; a repeat (the same commit pushed again) is ignored. `created_at` is the push
162- /// time as an RFC 3339 stamp.
163 pub async fn record_coauthored_commit(140 pub async fn record_coauthored_commit(
164 &self,141 &self,
165 user_id: &str,142 user_id: &str,
@@ -187,7 +164,6 @@ impl Store {
187 Ok(())164 Ok(())
188 }165 }
189 166
190- /// The distinct commit ids in `repo_id` whose stored message is not blank.
191 pub async fn coauthored_oids(&self, repo_id: &str) -> Result<Vec<String>> {167 pub async fn coauthored_oids(&self, repo_id: &str) -> Result<Vec<String>> {
192 let sql = "SELECT DISTINCT commit_oid FROM coauthored_commits \168 let sql = "SELECT DISTINCT commit_oid FROM coauthored_commits \
193 WHERE repo_id = ?1 AND summary <> '' ORDER BY commit_oid";169 WHERE repo_id = ?1 AND summary <> '' ORDER BY commit_oid";
@@ -196,8 +172,6 @@ impl Store {
196 fetch_all(&conn, sql, params, |row| col_text(row, 0)).await172 fetch_all(&conn, sql, params, |row| col_text(row, 0)).await
197 }173 }
198 174
199- /// Blanks the stored message of the commits `oids` in `repo_id`, for every user. The rows stay,
200- /// so contribution counts do not change.
201 pub async fn blank_coauthored(&self, repo_id: &str, oids: &[String]) -> Result<()> {175 pub async fn blank_coauthored(&self, repo_id: &str, oids: &[String]) -> Result<()> {
202 let conn = self.inner.conn.lock().await;176 let conn = self.inner.conn.lock().await;
203 for oid in oids {177 for oid in oids {
@@ -221,7 +195,6 @@ mod tests {
221 const OID: &str = "1111111111111111111111111111111111111111";195 const OID: &str = "1111111111111111111111111111111111111111";
222 const ZERO: &str = ZERO_OID_SHA1;196 const ZERO: &str = ZERO_OID_SHA1;
223 197
224- /// Backdates a row's `created_at`. Issues and comments are stamped "now" by the store.
225 async fn set_created_at(store: &Store, table: &str, id: &str, at: &str) {198 async fn set_created_at(store: &Store, table: &str, id: &str, at: &str) {
226 let conn = store.inner.conn.lock().await;199 let conn = store.inner.conn.lock().await;
227 conn.execute(200 conn.execute(
crates/forge-core/src/store/discussions.rsmodified+0 -57
@@ -1,7 +1,3 @@
1-//! Discussions and their comments. Numbers come from `repos.next_issue_number`, the counter that
2-//! issues and pull requests share, in the same transaction as the insert. Comments nest one level.
3-//! Locking, author checks and archive checks are the pages' job, since they depend on the viewer.
4-
5 use turso::transaction::Transaction;1 use turso::transaction::Transaction;
6 use turso::{Connection, Row, Value};2 use turso::{Connection, Row, Value};
7 3
@@ -40,8 +36,6 @@ fn map_discussion(row: &Row) -> Result<Discussion> {
40 })36 })
41 }37 }
42 38
43-/// Inbox rows of discussions joined with the discussion, its repo, owner and last actor. `?`
44-/// placeholders are appended by the callers.
45 const DISCUSSION_NOTE_SELECT: &str = "SELECT n.discussion_id, n.repo_id, o.username, r.name, \39 const DISCUSSION_NOTE_SELECT: &str = "SELECT n.discussion_id, n.repo_id, o.username, r.name, \
46 d.number, d.title, n.reason, a.username, n.unread, n.updated_at FROM discussion_notifications n \40 d.number, d.title, n.reason, a.username, n.unread, n.updated_at FROM discussion_notifications n \
47 JOIN discussions d ON d.id = n.discussion_id \41 JOIN discussions d ON d.id = n.discussion_id \
@@ -79,7 +73,6 @@ fn map_comment(row: &Row) -> Result<DiscussionComment> {
79 })73 })
80 }74 }
81 75
82-/// The discussion with this id, or `NotFound`.
83 async fn discussion_row(conn: &Connection, discussion_id: &str) -> Result<Discussion> {76 async fn discussion_row(conn: &Connection, discussion_id: &str) -> Result<Discussion> {
84 fetch_opt(77 fetch_opt(
85 conn,78 conn,
@@ -91,8 +84,6 @@ async fn discussion_row(conn: &Connection, discussion_id: &str) -> Result<Discus
91 .ok_or(Error::NotFound)84 .ok_or(Error::NotFound)
92 }85 }
93 86
94-/// Removes the discussion rows of a repo, with their comments, reactions and inbox rows. Called
95-/// from `Store::delete_repo`, children first.
96 pub(super) async fn delete_repo_discussion_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {87 pub(super) async fn delete_repo_discussion_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {
97 let id = repo_id.to_string();88 let id = repo_id.to_string();
98 for sql in [89 for sql in [
@@ -112,7 +103,6 @@ pub(super) async fn delete_repo_discussion_rows(tx: &Transaction<'_>, repo_id: &
112 }103 }
113 104
114 impl Store {105 impl Store {
115- /// Whether the repo has discussions turned on. Off by default.
116 pub async fn discussions_enabled(&self, repo_id: &str) -> Result<bool> {106 pub async fn discussions_enabled(&self, repo_id: &str) -> Result<bool> {
117 let conn = self.read_conn().await;107 let conn = self.read_conn().await;
118 let flag = fetch_opt(108 let flag = fetch_opt(
@@ -126,7 +116,6 @@ impl Store {
126 Ok(flag != 0)116 Ok(flag != 0)
127 }117 }
128 118
129- /// Turns discussions on or off for the repo. Existing discussions are kept while it is off.
130 pub async fn set_discussions_enabled(&self, repo_id: &str, enabled: bool) -> Result<()> {119 pub async fn set_discussions_enabled(&self, repo_id: &str, enabled: bool) -> Result<()> {
131 let conn = self.inner.conn.lock().await;120 let conn = self.inner.conn.lock().await;
132 let changed = conn121 let changed = conn
@@ -142,7 +131,6 @@ impl Store {
142 Ok(())131 Ok(())
143 }132 }
144 133
145- /// Creates a discussion with the repo's next number. Title and body are validated.
146 pub async fn create_discussion(134 pub async fn create_discussion(
147 &self,135 &self,
148 repo_id: &str,136 repo_id: &str,
@@ -207,7 +195,6 @@ impl Store {
207 finish(tx, outcome).await195 finish(tx, outcome).await
208 }196 }
209 197
210- /// The discussion with this number in the repo, if any.
211 pub async fn discussion_by_number(198 pub async fn discussion_by_number(
212 &self,199 &self,
213 repo_id: &str,200 repo_id: &str,
@@ -226,7 +213,6 @@ impl Store {
226 .await213 .await
227 }214 }
228 215
229- /// One page of discussions, most recently active first, plus the total number of matches.
230 pub async fn list_discussions(216 pub async fn list_discussions(
231 &self,217 &self,
232 repo_id: &str,218 repo_id: &str,
@@ -275,7 +261,6 @@ impl Store {
275 Ok((items, u64::try_from(total).unwrap_or(0)))261 Ok((items, u64::try_from(total).unwrap_or(0)))
276 }262 }
277 263
278- /// Replaces the title and body of a discussion.
279 pub async fn edit_discussion(264 pub async fn edit_discussion(
280 &self,265 &self,
281 discussion_id: &str,266 discussion_id: &str,
@@ -302,7 +287,6 @@ impl Store {
302 Ok(())287 Ok(())
303 }288 }
304 289
305- /// Locks or unlocks a discussion. Returns `false` when it was already in that state.
306 pub async fn set_discussion_locked(&self, discussion_id: &str, locked: bool) -> Result<bool> {290 pub async fn set_discussion_locked(&self, discussion_id: &str, locked: bool) -> Result<bool> {
307 let conn = self.inner.conn.lock().await;291 let conn = self.inner.conn.lock().await;
308 let changed = conn292 let changed = conn
@@ -319,8 +303,6 @@ impl Store {
319 Ok(false)303 Ok(false)
320 }304 }
321 305
322- /// Marks a comment as the answer, or clears the mark with `None`. Only Q&A discussions have an
323- /// answer, and the comment must be a live comment of that discussion.
324 pub async fn set_discussion_answer(306 pub async fn set_discussion_answer(
325 &self,307 &self,
326 discussion_id: &str,308 discussion_id: &str,
@@ -355,7 +337,6 @@ impl Store {
355 Ok(())337 Ok(())
356 }338 }
357 339
358- /// Deletes a discussion with its comments, reactions and inbox rows.
359 pub async fn delete_discussion(&self, discussion_id: &str) -> Result<()> {340 pub async fn delete_discussion(&self, discussion_id: &str) -> Result<()> {
360 let conn = self.inner.conn.lock().await;341 let conn = self.inner.conn.lock().await;
361 let tx = conn.unchecked_transaction().await.map_err(db_err)?;342 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -378,10 +359,6 @@ impl Store {
378 finish(tx, outcome).await359 finish(tx, outcome).await
379 }360 }
380 361
381- /// Adds a comment, or a reply when `parent_id` names a top-level live comment of the same
382- /// discussion. A reply to a reply is refused. Bumps the discussion's count and `updated_at`.
383- /// A locked discussion takes comments only from `triage` callers (Triage or higher). A comment
384- /// by someone other than the author also writes an inbox row for the author, reason `reply`.
385 pub async fn add_discussion_comment(362 pub async fn add_discussion_comment(
386 &self,363 &self,
387 discussion_id: &str,364 discussion_id: &str,
@@ -469,7 +446,6 @@ impl Store {
469 finish(tx, outcome).await446 finish(tx, outcome).await
470 }447 }
471 448
472- /// The comment with this id in this discussion, if any. Deleted comments are returned too.
473 pub async fn discussion_comment(449 pub async fn discussion_comment(
474 &self,450 &self,
475 discussion_id: &str,451 discussion_id: &str,
@@ -488,7 +464,6 @@ impl Store {
488 .await464 .await
489 }465 }
490 466
491- /// Replaces the body of a live comment.
492 pub async fn edit_discussion_comment(&self, comment_id: &str, body: &str) -> Result<()> {467 pub async fn edit_discussion_comment(&self, comment_id: &str, body: &str) -> Result<()> {
493 validate_comment(body)?;468 validate_comment(body)?;
494 let conn = self.inner.conn.lock().await;469 let conn = self.inner.conn.lock().await;
@@ -506,9 +481,6 @@ impl Store {
506 Ok(())481 Ok(())
507 }482 }
508 483
509- /// Deletes a comment. The row stays, so replies keep their parent: the body is emptied and
510- /// `deleted_at` is set. Its reactions go, and it stops being the answer. A comment that is
511- /// already deleted is left as it is.
512 pub async fn delete_discussion_comment(&self, comment_id: &str) -> Result<()> {484 pub async fn delete_discussion_comment(&self, comment_id: &str) -> Result<()> {
513 let conn = self.inner.conn.lock().await;485 let conn = self.inner.conn.lock().await;
514 let tx = conn.unchecked_transaction().await.map_err(db_err)?;486 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -557,8 +529,6 @@ impl Store {
557 finish(tx, outcome).await529 finish(tx, outcome).await
558 }530 }
559 531
560- /// Every comment of a discussion, oldest first, replies included. The page groups replies
561- /// under their parent.
562 pub async fn list_discussion_comments(532 pub async fn list_discussion_comments(
563 &self,533 &self,
564 discussion_id: &str,534 discussion_id: &str,
@@ -576,8 +546,6 @@ impl Store {
576 .await546 .await
577 }547 }
578 548
579- /// Adds or refreshes an inbox row for each user in `user_ids` (mentioned in a discussion). The
580- /// row goes back to unread and records who mentioned them.
581 pub async fn record_discussion_mentions(549 pub async fn record_discussion_mentions(
582 &self,550 &self,
583 repo_id: &str,551 repo_id: &str,
@@ -605,7 +573,6 @@ impl Store {
605 Ok(())573 Ok(())
606 }574 }
607 575
608- /// Unread inbox rows of a user for discussions: `(discussion_id, repo_id)` pairs, newest first.
609 pub async fn unread_discussion_mentions(&self, user_id: &str) -> Result<Vec<(String, String)>> {576 pub async fn unread_discussion_mentions(&self, user_id: &str) -> Result<Vec<(String, String)>> {
610 let conn = self.read_conn().await;577 let conn = self.read_conn().await;
611 fetch_all(578 fetch_all(
@@ -618,8 +585,6 @@ impl Store {
618 .await585 .await
619 }586 }
620 587
621- /// The user's inbox rows for discussions, newest first. `unread_only`, `before` and `limit`
622- /// mean what they mean in `list_notifications`.
623 pub async fn list_discussion_notifications(588 pub async fn list_discussion_notifications(
624 &self,589 &self,
625 user_id: &str,590 user_id: &str,
@@ -642,7 +607,6 @@ impl Store {
642 fetch_all(&conn, &sql, params, map_discussion_note).await607 fetch_all(&conn, &sql, params, map_discussion_note).await
643 }608 }
644 609
645- /// The user's inbox row for one discussion, if there is one.
646 pub async fn discussion_notification(610 pub async fn discussion_notification(
647 &self,611 &self,
648 user_id: &str,612 user_id: &str,
@@ -660,7 +624,6 @@ impl Store {
660 .await624 .await
661 }625 }
662 626
663- /// Marks the user's inbox row for one discussion read. Another user's row changes nothing.
664 pub async fn mark_discussion_notification_read(627 pub async fn mark_discussion_notification_read(
665 &self,628 &self,
666 user_id: &str,629 user_id: &str,
@@ -676,8 +639,6 @@ impl Store {
676 Ok(())639 Ok(())
677 }640 }
678 641
679- /// Marks the user's unread discussion rows read, in one repo when `repo_id` is given, otherwise
680- /// all of them.
681 pub async fn mark_all_discussion_notifications_read(642 pub async fn mark_all_discussion_notifications_read(
682 &self,643 &self,
683 user_id: &str,644 user_id: &str,
@@ -775,13 +736,10 @@ mod tests {
775 .id736 .id
776 }737 }
777 738
778- // Each scenario gets its own repo (numbers and lists stay isolated) and,
779- // where global per-user queries are asserted, its own users.
780 #[tokio::test]739 #[tokio::test]
781 async fn repo_level_rules_hold_in_each_scenario() {740 async fn repo_level_rules_hold_in_each_scenario() {
782 let fx = fixture().await;741 let fx = fixture().await;
783 742
784- // Scenario 1: discussions are off by default and toggle per repo.
785 let repo = fresh_repo(&fx.store, &fx.tahinli.id, "toggle").await;743 let repo = fresh_repo(&fx.store, &fx.tahinli.id, "toggle").await;
786 assert!(744 assert!(
787 !fx.store.discussions_enabled(&repo).await.unwrap(),745 !fx.store.discussions_enabled(&repo).await.unwrap(),
@@ -800,7 +758,6 @@ mod tests {
800 "toggle: unknown repo"758 "toggle: unknown repo"
801 );759 );
802 760
803- // Scenario 2: discussion numbers share the issue counter.
804 let repo = fresh_repo(&fx.store, &fx.tahinli.id, "numbers").await;761 let repo = fresh_repo(&fx.store, &fx.tahinli.id, "numbers").await;
805 let issue = fx762 let issue = fx
806 .store763 .store
@@ -827,7 +784,6 @@ mod tests {
827 "numbers: lookup by number"784 "numbers: lookup by number"
828 );785 );
829 786
830- // Scenario 3: blank titles are refused and listings filter by category.
831 let repo = fresh_repo(&fx.store, &fx.tahinli.id, "categories").await;787 let repo = fresh_repo(&fx.store, &fx.tahinli.id, "categories").await;
832 assert!(788 assert!(
833 matches!(789 matches!(
@@ -862,12 +818,10 @@ mod tests {
862 assert_eq!(qa[0].author, "Bob", "categories: qa author");818 assert_eq!(qa[0].author, "Bob", "categories: qa author");
863 }819 }
864 820
865- // Scenarios on one shared repo; every discussion is its own thread.
866 #[tokio::test]821 #[tokio::test]
867 async fn thread_rules_hold_in_each_scenario() {822 async fn thread_rules_hold_in_each_scenario() {
868 let fx = fixture().await;823 let fx = fixture().await;
869 824
870- // Scenario 1: comments nest one level deep and are counted.
871 let d = fx825 let d = fx
872 .store826 .store
873 .create_discussion(827 .create_discussion(
@@ -924,7 +878,6 @@ mod tests {
924 let all = fx.store.list_discussion_comments(&d.id).await.unwrap();878 let all = fx.store.list_discussion_comments(&d.id).await.unwrap();
925 assert_eq!(all.len(), 2, "nesting: listed comments");879 assert_eq!(all.len(), 2, "nesting: listed comments");
926 880
927- // Scenario 2: an answer is only accepted in Q&A and only from a live comment of it.
928 let qa = fx881 let qa = fx
929 .store882 .store
930 .create_discussion(&fx.repo_id, &fx.tahinli.id, DiscussionCategory::Qa, "q", "")883 .create_discussion(&fx.repo_id, &fx.tahinli.id, DiscussionCategory::Qa, "q", "")
@@ -993,7 +946,6 @@ mod tests {
993 "answer: cleared when the comment is deleted"946 "answer: cleared when the comment is deleted"
994 );947 );
995 948
996- // Scenario 3: lock reports changes and a deleted comment keeps its replies.
997 let d = fx949 let d = fx
998 .store950 .store
999 .create_discussion(951 .create_discussion(
@@ -1045,7 +997,6 @@ mod tests {
1045 "lock: reply survives"997 "lock: reply survives"
1046 );998 );
1047 999
1048- // Scenario 4: edit and delete remove or update the discussion and its rows.
1049 let d = fx1000 let d = fx
1050 .store1001 .store
1051 .create_discussion(1002 .create_discussion(
@@ -1100,7 +1051,6 @@ mod tests {
1100 "delete: second delete is not found"1051 "delete: second delete is not found"
1101 );1052 );
1102 1053
1103- // Scenario 5: a locked discussion takes comments only from triage.
1104 let d = fx1054 let d = fx
1105 .store1055 .store
1106 .create_discussion(1056 .create_discussion(
@@ -1139,12 +1089,10 @@ mod tests {
1139 .unwrap();1089 .unwrap();
1140 }1090 }
1141 1091
1142- // Each scenario uses fresh users so the global per-user inbox queries stay exact.
1143 #[tokio::test]1092 #[tokio::test]
1144 async fn inbox_rules_hold_in_each_scenario() {1093 async fn inbox_rules_hold_in_each_scenario() {
1145 let fx = fixture().await;1094 let fx = fixture().await;
1146 1095
1147- // Scenario 1: repeated mentions are stored once and show as unread.
1148 let ana = fx1096 let ana = fx
1149 .store1097 .store
1150 .create_user("Ana", None, "hash", false)1098 .create_user("Ana", None, "hash", false)
@@ -1182,7 +1130,6 @@ mod tests {
1182 "mentions: author is not mentioned"1130 "mentions: author is not mentioned"
1183 );1131 );
1184 1132
1185- // Scenario 2: replies, mentions and mark-read reach the owner's inbox.
1186 let cora = fx1133 let cora = fx
1187 .store1134 .store
1188 .create_user("Cora", None, "hash", false)1135 .create_user("Cora", None, "hash", false)
@@ -1199,12 +1146,10 @@ mod tests {
1199 .create_discussion(&repo, &cora.id, DiscussionCategory::Qa, "Q", "")1146 .create_discussion(&repo, &cora.id, DiscussionCategory::Qa, "Q", "")
1200 .await1147 .await
1201 .unwrap();1148 .unwrap();
1202- // Dev's comment on Cora's discussion gives Cora a reply row.
1203 fx.store1149 fx.store
1204 .add_discussion_comment(&d.id, &dev.id, None, "answer", false)1150 .add_discussion_comment(&d.id, &dev.id, None, "answer", false)
1205 .await1151 .await
1206 .unwrap();1152 .unwrap();
1207- // Cora's own comment gives her nothing.
1208 fx.store1153 fx.store
1209 .add_discussion_comment(&d.id, &cora.id, None, "thanks", false)1154 .add_discussion_comment(&d.id, &cora.id, None, "thanks", false)
1210 .await1155 .await
@@ -1225,7 +1170,6 @@ mod tests {
1225 "replies: last actor"1170 "replies: last actor"
1226 );1171 );
1227 1172
1228- // A mention upgrades the row, and a later reply does not downgrade it.
1229 fx.store1173 fx.store
1230 .record_discussion_mentions(&repo, &d.id, &dev.id, std::slice::from_ref(&cora.id))1174 .record_discussion_mentions(&repo, &d.id, &dev.id, std::slice::from_ref(&cora.id))
1231 .await1175 .await
@@ -1251,7 +1195,6 @@ mod tests {
1251 "upgrade: unread count"1195 "upgrade: unread count"
1252 );1196 );
1253 1197
1254- // Another user's mark-read changes nothing; the owner's mark-all clears it.
1255 fx.store1198 fx.store
1256 .mark_discussion_notification_read(&dev.id, &d.id)1199 .mark_discussion_notification_read(&dev.id, &d.id)
1257 .await1200 .await
crates/forge-core/src/store/edit_history_read.rsmodified+0 -13
@@ -1,13 +1,8 @@
1-//! Reads of the edit history written by `edit_issue`, `edit_comment` and `edit_review_comment`.
2-//! Each row holds the text an edit replaced, so a row's text is the version that was live before
3-//! `edited_at`, and its editor is the person who replaced it.
4-
5 use std::collections::HashMap;1 use std::collections::HashMap;
6 2
7 use super::{IN_CHUNK, Store, col_int, col_opt_text, col_text, fetch_all, fetch_opt, placeholders};3 use super::{IN_CHUNK, Store, col_int, col_opt_text, col_text, fetch_all, fetch_opt, placeholders};
8 use crate::error::Result;4 use crate::error::Result;
9 5
10-/// The kinds of target that have edit history. `as_str` is the stored text.
11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]6 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12 pub enum EditTarget {7 pub enum EditTarget {
13 Issue,8 Issue,
@@ -25,20 +20,16 @@ impl EditTarget {
25 }20 }
26 }21 }
27 22
28-/// One previous version of an issue, pull request, comment or review comment.
29 #[derive(Debug, Clone, PartialEq)]23 #[derive(Debug, Clone, PartialEq)]
30 pub struct EditVersion {24 pub struct EditVersion {
31 pub id: String,25 pub id: String,
32- /// The username of the person who made the edit that replaced this version.
33 pub editor_name: String,26 pub editor_name: String,
34 pub edited_at: String,27 pub edited_at: String,
35- /// The title it had, for issues and pull requests.
36 pub old_title: Option<String>,28 pub old_title: Option<String>,
37 pub old_body: String,29 pub old_body: String,
38 }30 }
39 31
40 impl Store {32 impl Store {
41- /// The previous versions of one target, newest first.
42 pub async fn edit_history(33 pub async fn edit_history(
43 &self,34 &self,
44 target_kind: EditTarget,35 target_kind: EditTarget,
@@ -65,8 +56,6 @@ impl Store {
65 .await56 .await
66 }57 }
67 58
68- /// How many previous versions each target has, keyed by target id. Targets with no edits are
69- /// absent from the map. One query per 500 ids.
70 pub async fn edit_count(59 pub async fn edit_count(
71 &self,60 &self,
72 target_kind: EditTarget,61 target_kind: EditTarget,
@@ -96,8 +85,6 @@ impl Store {
96 Ok(out)85 Ok(out)
97 }86 }
98 87
99- /// The issue a comment, review comment or issue belongs to, by target id. `None` when the
100- /// target does not exist (a deleted comment has no history either).
101 pub async fn edit_target_issue(88 pub async fn edit_target_issue(
102 &self,89 &self,
103 target_kind: EditTarget,90 target_kind: EditTarget,
crates/forge-core/src/store/exports.rsmodified+0 -8
@@ -1,6 +1,3 @@
1-//! Storage for per-user data exports (migration 0051). The archive bytes live on disk; this layer
2-//! tracks the state and the expiry.
3-
4 use std::time::Duration;1 use std::time::Duration;
5 2
6 use turso::{Row, Value};3 use turso::{Row, Value};
@@ -62,7 +59,6 @@ fn map_export(row: &Row) -> Result<DataExport> {
62 }59 }
63 60
64 impl Store {61 impl Store {
65- /// Starts an export. It expires `ttl` from now; becoming ready restarts the clock.
66 pub async fn create_export(&self, user_id: &str, ttl: Duration) -> Result<DataExport> {62 pub async fn create_export(&self, user_id: &str, ttl: Duration) -> Result<DataExport> {
67 let id = new_id();63 let id = new_id();
68 let now = now_stamp();64 let now = now_stamp();
@@ -91,7 +87,6 @@ impl Store {
91 .await87 .await
92 }88 }
93 89
94- /// The user's exports, newest first.
95 pub async fn list_exports(&self, user_id: &str) -> Result<Vec<DataExport>> {90 pub async fn list_exports(&self, user_id: &str) -> Result<Vec<DataExport>> {
96 let conn = self.inner.conn.lock().await;91 let conn = self.inner.conn.lock().await;
97 fetch_all(92 fetch_all(
@@ -105,7 +100,6 @@ impl Store {
105 .await100 .await
106 }101 }
107 102
108- /// Marks an export ready and restarts its expiry from now.
109 pub async fn mark_export_ready(&self, id: &str, size: i64, ttl: Duration) -> Result<()> {103 pub async fn mark_export_ready(&self, id: &str, size: i64, ttl: Duration) -> Result<()> {
110 let conn = self.inner.conn.lock().await;104 let conn = self.inner.conn.lock().await;
111 conn.execute(105 conn.execute(
@@ -134,7 +128,6 @@ impl Store {
134 Ok(())128 Ok(())
135 }129 }
136 130
137- /// Exports whose expiry has passed at `now`.
138 pub async fn expired_exports(&self, now: &str) -> Result<Vec<DataExport>> {131 pub async fn expired_exports(&self, now: &str) -> Result<Vec<DataExport>> {
139 let conn = self.inner.conn.lock().await;132 let conn = self.inner.conn.lock().await;
140 fetch_all(133 fetch_all(
@@ -154,7 +147,6 @@ impl Store {
154 Ok(())147 Ok(())
155 }148 }
156 149
157- /// Fails exports that were still building when the process stopped. Called at boot.
158 pub async fn fail_interrupted_exports(&self) -> Result<u64> {150 pub async fn fail_interrupted_exports(&self) -> Result<u64> {
159 let conn = self.inner.conn.lock().await;151 let conn = self.inner.conn.lock().await;
160 conn.execute(152 conn.execute(
crates/forge-core/src/store/health.rsmodified+0 -7
@@ -1,15 +1,9 @@
1-//! Cheap counts for the admin health page.
2-
3 use super::{Store, col_int, fetch_opt};1 use super::{Store, col_int, fetch_opt};
4 use crate::error::{Error, Result};2 use crate::error::{Error, Result};
5 use crate::time::{stamp_ago, stamp_to_unix};3 use crate::time::{stamp_ago, stamp_to_unix};
6 4
7-/// Window in which a runner's last report counts as online.
8 pub const RUNNER_ONLINE_SECS: i64 = 90;5 pub const RUNNER_ONLINE_SECS: i64 = 90;
9 6
10-/// Whether a runner counts as online at `now_unix`: enabled, and its last report within
11-/// [`RUNNER_ONLINE_SECS`]. The runners page dot and the live signal of the runners page both use
12-/// this one rule.
13 pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool {7 pub fn runner_is_online(disabled: bool, last_seen_at: Option<&str>, now_unix: i64) -> bool {
14 !disabled8 !disabled
15 && last_seen_at9 && last_seen_at
@@ -27,7 +21,6 @@ pub struct HealthCounts {
27 }21 }
28 22
29 impl Store {23 impl Store {
30- /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries.
31 pub async fn health_counts(&self) -> Result<HealthCounts> {24 pub async fn health_counts(&self) -> Result<HealthCounts> {
32 let conn = self.read_conn().await;25 let conn = self.read_conn().await;
33 let since = stamp_ago(std::time::Duration::from_secs(26 let since = stamp_ago(std::time::Duration::from_secs(
crates/forge-core/src/store/imports.rsmodified+0 -16
@@ -1,16 +1,11 @@
1-//! Storage for repository import jobs, their progress log and the remote-to-local id map
2-//! (migration 0050). No remote credential is ever stored here.
3-
4 use turso::{Row, Value};1 use turso::{Row, Value};
5 2
6 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text};3 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text};
7 use crate::error::{Error, Result};4 use crate::error::{Error, Result};
8 use crate::time::now_stamp;5 use crate::time::now_stamp;
9 6
10-/// Most progress lines kept per job. Older ones are dropped as new ones arrive.
11 pub const MAX_EVENTS: i64 = 500;7 pub const MAX_EVENTS: i64 = 500;
12 8
13-/// Where a job is.
14 #[derive(Debug, Clone, Copy, PartialEq, Eq)]9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15 pub enum ImportState {10 pub enum ImportState {
16 Queued,11 Queued,
@@ -70,7 +65,6 @@ pub struct ImportEvent {
70 pub created_at: String,65 pub created_at: String,
71 }66 }
72 67
73-/// The remote object a local row came from.
74 #[derive(Debug, Clone, PartialEq)]68 #[derive(Debug, Clone, PartialEq)]
75 pub struct ImportOrigin {69 pub struct ImportOrigin {
76 pub local_id: String,70 pub local_id: String,
@@ -101,7 +95,6 @@ fn map_job(row: &Row) -> Result<ImportJob> {
101 }95 }
102 96
103 impl Store {97 impl Store {
104- /// Creates a queued job. `source_ref` must not hold a credential.
105 pub async fn create_import_job(98 pub async fn create_import_job(
106 &self,99 &self,
107 user_id: &str,100 user_id: &str,
@@ -144,7 +137,6 @@ impl Store {
144 .await137 .await
145 }138 }
146 139
147- /// The user's jobs, newest first.
148 pub async fn list_import_jobs(&self, user_id: &str, limit: u32) -> Result<Vec<ImportJob>> {140 pub async fn list_import_jobs(&self, user_id: &str, limit: u32) -> Result<Vec<ImportJob>> {
149 let conn = self.inner.conn.lock().await;141 let conn = self.inner.conn.lock().await;
150 fetch_all(142 fetch_all(
@@ -159,7 +151,6 @@ impl Store {
159 .await151 .await
160 }152 }
161 153
162- /// The unfinished job of a repo, if any. A repo has at most one running import.
163 pub async fn active_import_for_repo(&self, repo_id: &str) -> Result<Option<ImportJob>> {154 pub async fn active_import_for_repo(&self, repo_id: &str) -> Result<Option<ImportJob>> {
164 let conn = self.inner.conn.lock().await;155 let conn = self.inner.conn.lock().await;
165 fetch_opt(156 fetch_opt(
@@ -174,7 +165,6 @@ impl Store {
174 .await165 .await
175 }166 }
176 167
177- /// Moves a job to `state`. A finished state stamps `finished_at`. A retry clears the error.
178 pub async fn set_import_state(168 pub async fn set_import_state(
179 &self,169 &self,
180 id: &str,170 id: &str,
@@ -220,7 +210,6 @@ impl Store {
220 Ok(changed > 0)210 Ok(changed > 0)
221 }211 }
222 212
223- /// Records the current stage and how far it is.
224 pub async fn set_import_progress(213 pub async fn set_import_progress(
225 &self,214 &self,
226 id: &str,215 id: &str,
@@ -244,7 +233,6 @@ impl Store {
244 Ok(())233 Ok(())
245 }234 }
246 235
247- /// Appends a progress line and drops the oldest beyond [`MAX_EVENTS`].
248 pub async fn add_import_event(&self, job_id: &str, level: &str, message: &str) -> Result<()> {236 pub async fn add_import_event(&self, job_id: &str, level: &str, message: &str) -> Result<()> {
249 let conn = self.inner.conn.lock().await;237 let conn = self.inner.conn.lock().await;
250 let next = fetch_opt(238 let next = fetch_opt(
@@ -277,7 +265,6 @@ impl Store {
277 Ok(())265 Ok(())
278 }266 }
279 267
280- /// The newest `limit` lines of a job, oldest first.
281 pub async fn list_import_events(&self, job_id: &str, limit: u32) -> Result<Vec<ImportEvent>> {268 pub async fn list_import_events(&self, job_id: &str, limit: u32) -> Result<Vec<ImportEvent>> {
282 let conn = self.inner.conn.lock().await;269 let conn = self.inner.conn.lock().await;
283 let mut rows = fetch_all(270 let mut rows = fetch_all(
@@ -299,7 +286,6 @@ impl Store {
299 Ok(rows)286 Ok(rows)
300 }287 }
301 288
302- /// The local row a remote object was imported as, if it was.
303 pub async fn import_origin(289 pub async fn import_origin(
304 &self,290 &self,
305 repo_id: &str,291 repo_id: &str,
@@ -323,7 +309,6 @@ impl Store {
323 .await309 .await
324 }310 }
325 311
326- /// Records that a remote object became `origin.local_id`. Idempotent.
327 pub async fn record_import_origin(312 pub async fn record_import_origin(
328 &self,313 &self,
329 repo_id: &str,314 repo_id: &str,
@@ -351,7 +336,6 @@ impl Store {
351 Ok(())336 Ok(())
352 }337 }
353 338
354- /// Fails every job that was queued or running when the process stopped. Called at boot.
355 pub async fn fail_interrupted_imports(&self) -> Result<u64> {339 pub async fn fail_interrupted_imports(&self) -> Result<u64> {
356 let now = now_stamp();340 let now = now_stamp();
357 let conn = self.inner.conn.lock().await;341 let conn = self.inner.conn.lock().await;
crates/forge-core/src/store/labels.rsmodified+0 -68
@@ -1,6 +1,3 @@
1-//! Labels, issue label/assignee/milestone links, and milestones. Every function is scoped by
2-//! repo: an id that belongs to another repo is `NotFound` or `Invalid`, never acted on.
3-
4 use std::collections::{BTreeMap, BTreeSet};1 use std::collections::{BTreeMap, BTreeSet};
5 2
6 use jiff::civil::Date;3 use jiff::civil::Date;
@@ -21,13 +18,11 @@ use crate::model::User;
21 use crate::names::normalize_name;18 use crate::names::normalize_name;
22 use crate::time::now_stamp;19 use crate::time::now_stamp;
23 20
24-/// Most labels one repo can have.
25 pub const MAX_LABELS: i64 = 500;21 pub const MAX_LABELS: i64 = 500;
26 22
27 const LABEL_TAKEN: &str = "a label with that name already exists";23 const LABEL_TAKEN: &str = "a label with that name already exists";
28 const MILESTONE_TAKEN: &str = "a milestone with that title already exists";24 const MILESTONE_TAKEN: &str = "a milestone with that title already exists";
29 25
30-/// Labels a new repo starts with: (name, color, description).
31 pub const DEFAULT_LABELS: [(&str, &str, &str); 9] = [26 pub const DEFAULT_LABELS: [(&str, &str, &str); 9] = [
32 ("bug", "#d73a4a", "Something isn't working"),27 ("bug", "#d73a4a", "Something isn't working"),
33 (28 (
@@ -49,18 +44,13 @@ pub const DEFAULT_LABELS: [(&str, &str, &str); 9] = [
49 ];44 ];
50 45
51 const LABEL_COLS: &str = "id, repo_id, name, color, description";46 const LABEL_COLS: &str = "id, repo_id, name, color, description";
52-/// One grouped query: each milestone with its open and closed issue counts. Joining on
53-/// `repo_id` as well lets the lookup use the issues index.
54 const MILESTONE_SELECT: &str = "SELECT m.id, m.repo_id, m.title, m.description, m.due_on, m.state, \47 const MILESTONE_SELECT: &str = "SELECT m.id, m.repo_id, m.title, m.description, m.due_on, m.state, \
55 m.created_at, m.closed_at, \48 m.created_at, m.closed_at, \
56 COUNT(CASE WHEN i.state = 'open' THEN 1 END), COUNT(CASE WHEN i.state = 'closed' THEN 1 END) \49 COUNT(CASE WHEN i.state = 'open' THEN 1 END), COUNT(CASE WHEN i.state = 'closed' THEN 1 END) \
57 FROM milestones m LEFT JOIN issues i ON i.repo_id = m.repo_id AND i.milestone_id = m.id \50 FROM milestones m LEFT JOIN issues i ON i.repo_id = m.repo_id AND i.milestone_id = m.id \
58 AND i.kind = 'issue'";51 AND i.kind = 'issue'";
59 52
60-// labels
61-
62 impl Store {53 impl Store {
63- /// The repo's labels, ordered by case-folded name.
64 pub async fn list_labels(&self, repo_id: &str) -> Result<Vec<Label>> {54 pub async fn list_labels(&self, repo_id: &str) -> Result<Vec<Label>> {
65 let conn = self.read_conn().await;55 let conn = self.read_conn().await;
66 fetch_all(56 fetch_all(
@@ -72,8 +62,6 @@ impl Store {
72 .await62 .await
73 }63 }
74 64
75- /// Open issue count per label of `repo_id`, as `(label_id, count)`, in one grouped query.
76- /// Labels with no open issues are included with 0.
77 pub async fn label_open_counts(&self, repo_id: &str) -> Result<Vec<(String, i64)>> {65 pub async fn label_open_counts(&self, repo_id: &str) -> Result<Vec<(String, i64)>> {
78 let conn = self.read_conn().await;66 let conn = self.read_conn().await;
79 fetch_all(67 fetch_all(
@@ -88,7 +76,6 @@ impl Store {
88 .await76 .await
89 }77 }
90 78
91- /// Creates a label. A name that folds to an existing one in the same repo is `Conflict`.
92 pub async fn create_label(79 pub async fn create_label(
93 &self,80 &self,
94 repo_id: &str,81 repo_id: &str,
@@ -136,8 +123,6 @@ impl Store {
136 Ok(label)123 Ok(label)
137 }124 }
138 125
139- /// Adds the default labels to `repo_id`, skipping any whose name the repo already has.
140- /// Returns how many were created. Running it again creates nothing.
141 pub async fn create_default_labels(&self, repo_id: &str) -> Result<usize> {126 pub async fn create_default_labels(&self, repo_id: &str) -> Result<usize> {
142 let mut created = 0;127 let mut created = 0;
143 for (name, color, description) in DEFAULT_LABELS {128 for (name, color, description) in DEFAULT_LABELS {
@@ -150,7 +135,6 @@ impl Store {
150 Ok(created)135 Ok(created)
151 }136 }
152 137
153- /// Updates a label in place. `NotFound` if the label is not in `repo_id`.
154 pub async fn update_label(138 pub async fn update_label(
155 &self,139 &self,
156 repo_id: &str,140 repo_id: &str,
@@ -183,8 +167,6 @@ impl Store {
183 Ok(())167 Ok(())
184 }168 }
185 169
186- /// Deletes a label and its issue links in one transaction. `NotFound` if the label is not
187- /// in `repo_id`; nothing is changed then.
188 pub async fn delete_label(&self, repo_id: &str, label_id: &str) -> Result<()> {170 pub async fn delete_label(&self, repo_id: &str, label_id: &str) -> Result<()> {
189 let conn = self.inner.conn.lock().await;171 let conn = self.inner.conn.lock().await;
190 let tx = conn.unchecked_transaction().await.map_err(db_err)?;172 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -211,7 +193,6 @@ impl Store {
211 finish(tx, outcome).await193 finish(tx, outcome).await
212 }194 }
213 195
214- /// The labels on one issue, ordered by case-folded name.
215 pub async fn issue_labels(&self, issue_id: &str) -> Result<Vec<Label>> {196 pub async fn issue_labels(&self, issue_id: &str) -> Result<Vec<Label>> {
216 let conn = self.read_conn().await;197 let conn = self.read_conn().await;
217 fetch_all(198 fetch_all(
@@ -224,9 +205,6 @@ impl Store {
224 .await205 .await
225 }206 }
226 207
227- /// Replaces the issue's label set. Adds and removes happen in one transaction, with one
228- /// `labeled` or `unlabeled` event per change. Every id must be a label of the issue's repo;
229- /// otherwise `Invalid` and nothing changes.
230 pub async fn set_issue_labels(208 pub async fn set_issue_labels(
231 &self,209 &self,
232 issue_id: &str,210 issue_id: &str,
@@ -314,7 +292,6 @@ impl Store {
314 finish(tx, outcome).await292 finish(tx, outcome).await
315 }293 }
316 294
317- /// The issue's assignees as `(user id, display username)`, ordered by name.
318 pub async fn issue_assignees(&self, issue_id: &str) -> Result<Vec<(String, String)>> {295 pub async fn issue_assignees(&self, issue_id: &str) -> Result<Vec<(String, String)>> {
319 let conn = self.read_conn().await;296 let conn = self.read_conn().await;
320 fetch_all(297 fetch_all(
@@ -327,9 +304,6 @@ impl Store {
327 .await304 .await
328 }305 }
329 306
330- /// Replaces the issue's assignees. Usernames are trimmed and deduplicated case-insensitively
331- /// (the first spelling wins). At most `MAX_ASSIGNEES`. Each user must be able to Read the
332- /// repo, otherwise `Invalid`. Records `assigned` and `unassigned` events.
333 pub async fn set_issue_assignees(307 pub async fn set_issue_assignees(
334 &self,308 &self,
335 issue_id: &str,309 issue_id: &str,
@@ -350,7 +324,6 @@ impl Store {
350 )));324 )));
351 }325 }
352 326
353- // These helpers take the connection lock themselves, so they run before it is held.
354 let repo_id = {327 let repo_id = {
355 let conn = self.inner.conn.lock().await;328 let conn = self.inner.conn.lock().await;
356 issue_repo_id(&conn, issue_id).await?329 issue_repo_id(&conn, issue_id).await?
@@ -431,9 +404,6 @@ impl Store {
431 finish(tx, outcome).await404 finish(tx, outcome).await
432 }405 }
433 406
434- // milestones
435-
436- /// The repo's milestones ordered by title. `state` filters when given.
437 pub async fn list_milestones(407 pub async fn list_milestones(
438 &self,408 &self,
439 repo_id: &str,409 repo_id: &str,
@@ -453,7 +423,6 @@ impl Store {
453 .await423 .await
454 }424 }
455 425
456- /// One milestone with its issue counts, or `None` if it is not in `repo_id`.
457 pub async fn milestone_by_id(&self, repo_id: &str, id: &str) -> Result<Option<Milestone>> {426 pub async fn milestone_by_id(&self, repo_id: &str, id: &str) -> Result<Option<Milestone>> {
458 let conn = self.read_conn().await;427 let conn = self.read_conn().await;
459 fetch_opt(428 fetch_opt(
@@ -465,7 +434,6 @@ impl Store {
465 .await434 .await
466 }435 }
467 436
468- /// Creates an open milestone. `due_on` must be `YYYY-MM-DD` when given.
469 pub async fn create_milestone(437 pub async fn create_milestone(
470 &self,438 &self,
471 repo_id: &str,439 repo_id: &str,
@@ -507,8 +475,6 @@ impl Store {
507 Ok(milestone)475 Ok(milestone)
508 }476 }
509 477
510- /// Updates a milestone. `closed_at` is set when it becomes closed and cleared when reopened.
511- /// `NotFound` if the milestone is not in `repo_id`.
512 pub async fn update_milestone(478 pub async fn update_milestone(
513 &self,479 &self,
514 repo_id: &str,480 repo_id: &str,
@@ -546,8 +512,6 @@ impl Store {
546 Ok(())512 Ok(())
547 }513 }
548 514
549- /// Deletes a milestone. Its issues stay, with `milestone_id` set to NULL first. `NotFound`
550- /// (and nothing changed) if the milestone is not in `repo_id`.
551 pub async fn delete_milestone(&self, repo_id: &str, id: &str) -> Result<()> {515 pub async fn delete_milestone(&self, repo_id: &str, id: &str) -> Result<()> {
552 let conn = self.inner.conn.lock().await;516 let conn = self.inner.conn.lock().await;
553 let tx = conn.unchecked_transaction().await.map_err(db_err)?;517 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -574,9 +538,6 @@ impl Store {
574 finish(tx, outcome).await538 finish(tx, outcome).await
575 }539 }
576 540
577- /// Sets or clears the issue's milestone. The milestone must belong to the issue's repo
578- /// (`Invalid` otherwise). Records `demilestoned` for the old one and `milestoned` for the
579- /// new one, each with `{"title": ...}`. Setting the same value again changes nothing.
580 pub async fn set_issue_milestone(541 pub async fn set_issue_milestone(
581 &self,542 &self,
582 issue_id: &str,543 issue_id: &str,
@@ -652,8 +613,6 @@ impl Store {
652 }613 }
653 }614 }
654 615
655-// helpers
656-
657 fn map_label(row: &Row) -> Result<Label> {616 fn map_label(row: &Row) -> Result<Label> {
658 Ok(Label {617 Ok(Label {
659 id: col_text(row, 0)?,618 id: col_text(row, 0)?,
@@ -679,8 +638,6 @@ fn map_milestone(row: &Row) -> Result<Milestone> {
679 })638 })
680 }639 }
681 640
682-/// `YYYY-MM-DD` and a real calendar date. The shape check rejects inputs such as a full
683-/// datetime that `Date::from_str` might otherwise accept.
684 fn validate_due_on(due_on: Option<&str>) -> Result<()> {641 fn validate_due_on(due_on: Option<&str>) -> Result<()> {
685 let Some(s) = due_on else {642 let Some(s) = due_on else {
686 return Ok(());643 return Ok(());
@@ -700,7 +657,6 @@ fn validate_due_on(due_on: Option<&str>) -> Result<()> {
700 }657 }
701 }658 }
702 659
703-/// The repo of an issue, or `NotFound`.
704 async fn issue_repo_id(conn: &Connection, issue_id: &str) -> Result<String> {660 async fn issue_repo_id(conn: &Connection, issue_id: &str) -> Result<String> {
705 fetch_opt(661 fetch_opt(
706 conn,662 conn,
@@ -742,7 +698,6 @@ mod tests {
742 }698 }
743 }699 }
744 700
745- /// A repo of its own, so label and milestone lists stay exact per scenario.
746 async fn fresh_repo(store: &Store, owner: &str, name: &str) -> String {701 async fn fresh_repo(store: &Store, owner: &str, name: &str) -> String {
747 store702 store
748 .create_repo(owner, name, "", Visibility::Public, "main")703 .create_repo(owner, name, "", Visibility::Public, "main")
@@ -751,7 +706,6 @@ mod tests {
751 .id706 .id
752 }707 }
753 708
754- /// Data of every event of `kind`.
755 fn data_of(events: &[IssueEvent], kind: &str) -> Vec<Value> {709 fn data_of(events: &[IssueEvent], kind: &str) -> Vec<Value> {
756 events710 events
757 .iter()711 .iter()
@@ -764,15 +718,12 @@ mod tests {
764 labels.iter().map(|l| l.name.as_str()).collect()718 labels.iter().map(|l| l.name.as_str()).collect()
765 }719 }
766 720
767- // Repo labels: creating, defaults, listing, updating and deleting.
768- // Every scenario has its own repos, so lists and counts stay exact.
769 #[tokio::test]721 #[tokio::test]
770 async fn label_rules_hold_in_each_scenario() {722 async fn label_rules_hold_in_each_scenario() {
771 let fx = fixture().await;723 let fx = fixture().await;
772 let s = &fx.store;724 let s = &fx.store;
773 let owner = &fx.tahinli.id;725 let owner = &fx.tahinli.id;
774 726
775- // Scenario 1: names are trimmed and colours normalized; duplicates are refused.
776 let repo = fresh_repo(s, owner, "labels-create").await;727 let repo = fresh_repo(s, owner, "labels-create").await;
777 let other = fresh_repo(s, owner, "labels-create-other").await;728 let other = fresh_repo(s, owner, "labels-create-other").await;
778 let label = s729 let label = s
@@ -793,10 +744,8 @@ mod tests {
793 s.create_label(&repo, "bad", "red", "").await.is_err(),744 s.create_label(&repo, "bad", "red", "").await.is_err(),
794 "create: colour must be hex"745 "create: colour must be hex"
795 );746 );
796- // The same name in another repo is a different label.
797 s.create_label(&other, "bug", "#000000", "").await.unwrap();747 s.create_label(&other, "bug", "#000000", "").await.unwrap();
798 748
799- // Scenario 2: default labels are added once and a second run adds nothing.
800 let repo = fresh_repo(s, owner, "labels-defaults").await;749 let repo = fresh_repo(s, owner, "labels-defaults").await;
801 assert_eq!(750 assert_eq!(
802 s.create_default_labels(&repo).await.unwrap(),751 s.create_default_labels(&repo).await.unwrap(),
@@ -822,7 +771,6 @@ mod tests {
822 "defaults: existing rows kept"771 "defaults: existing rows kept"
823 );772 );
824 773
825- // Scenario 3: defaults skip names already taken.
826 let repo = fresh_repo(s, owner, "labels-taken").await;774 let repo = fresh_repo(s, owner, "labels-taken").await;
827 s.create_label(&repo, "BUG", "#000000", "mine")775 s.create_label(&repo, "BUG", "#000000", "mine")
828 .await776 .await
@@ -838,7 +786,6 @@ mod tests {
838 assert_eq!(bug.color, "#000000", "taken: own colour kept");786 assert_eq!(bug.color, "#000000", "taken: own colour kept");
839 assert_eq!(bug.description, "mine", "taken: own description kept");787 assert_eq!(bug.description, "mine", "taken: own description kept");
840 788
841- // Scenario 4: listing is sorted and scoped to the repo.
842 let repo = fresh_repo(s, owner, "labels-sorted").await;789 let repo = fresh_repo(s, owner, "labels-sorted").await;
843 let other = fresh_repo(s, owner, "labels-sorted-other").await;790 let other = fresh_repo(s, owner, "labels-sorted-other").await;
844 s.create_label(&repo, "b", "#111111", "").await.unwrap();791 s.create_label(&repo, "b", "#111111", "").await.unwrap();
@@ -855,7 +802,6 @@ mod tests {
855 "sorted: other repo only has its own"802 "sorted: other repo only has its own"
856 );803 );
857 804
858- // Scenario 5: update checks conflicts and scope.
859 let repo = fresh_repo(s, owner, "labels-update").await;805 let repo = fresh_repo(s, owner, "labels-update").await;
860 let other = fresh_repo(s, owner, "labels-update-other").await;806 let other = fresh_repo(s, owner, "labels-update-other").await;
861 let bug = s.create_label(&repo, "bug", "#111111", "").await.unwrap();807 let bug = s.create_label(&repo, "bug", "#111111", "").await.unwrap();
@@ -888,7 +834,6 @@ mod tests {
888 "update: foreign label untouched"834 "update: foreign label untouched"
889 );835 );
890 836
891- // Scenario 6: delete removes links and is scoped to the repo.
892 let repo = fresh_repo(s, owner, "labels-delete").await;837 let repo = fresh_repo(s, owner, "labels-delete").await;
893 let other = fresh_repo(s, owner, "labels-delete-other").await;838 let other = fresh_repo(s, owner, "labels-delete-other").await;
894 let bug = s.create_label(&repo, "bug", "#111111", "").await.unwrap();839 let bug = s.create_label(&repo, "bug", "#111111", "").await.unwrap();
@@ -919,14 +864,12 @@ mod tests {
919 );864 );
920 }865 }
921 866
922- // Labels and assignees on one issue. Each scenario has its own repo.
923 #[tokio::test]867 #[tokio::test]
924 async fn issue_label_and_assignee_rules_hold_in_each_scenario() {868 async fn issue_label_and_assignee_rules_hold_in_each_scenario() {
925 let fx = fixture().await;869 let fx = fixture().await;
926 let s = &fx.store;870 let s = &fx.store;
927 let owner = &fx.tahinli.id;871 let owner = &fx.tahinli.id;
928 872
929- // Scenario 1: label changes are diffed and recorded as events.
930 let repo = fresh_repo(s, owner, "issue-labels").await;873 let repo = fresh_repo(s, owner, "issue-labels").await;
931 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();874 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();
932 let a = s.create_label(&repo, "a", "#111111", "").await.unwrap();875 let a = s.create_label(&repo, "a", "#111111", "").await.unwrap();
@@ -968,7 +911,6 @@ mod tests {
968 "labels: resulting set"911 "labels: resulting set"
969 );912 );
970 913
971- // Setting the same set again changes nothing and records nothing.
972 s.set_issue_labels(&issue.id, owner, &[c.id.clone(), b.id.clone()])914 s.set_issue_labels(&issue.id, owner, &[c.id.clone(), b.id.clone()])
973 .await915 .await
974 .unwrap();916 .unwrap();
@@ -984,7 +926,6 @@ mod tests {
984 "labels: same set, no remove"926 "labels: same set, no remove"
985 );927 );
986 928
987- // Scenario 2: a label from another repo rejects the whole write.
988 let repo = fresh_repo(s, owner, "issue-labels-repo").await;929 let repo = fresh_repo(s, owner, "issue-labels-repo").await;
989 let other = fresh_repo(s, owner, "issue-labels-other").await;930 let other = fresh_repo(s, owner, "issue-labels-other").await;
990 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();931 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();
@@ -1014,7 +955,6 @@ mod tests {
1014 "foreign: unknown issue"955 "foreign: unknown issue"
1015 );956 );
1016 957
1017- // Scenario 3: assignees are deduplicated, resolved and recorded.
1018 let repo = fresh_repo(s, owner, "assignees").await;958 let repo = fresh_repo(s, owner, "assignees").await;
1019 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();959 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();
1020 let input = [960 let input = [
@@ -1057,7 +997,6 @@ mod tests {
1057 "assignees: Bob removed"997 "assignees: Bob removed"
1058 );998 );
1059 999
1060- // Scenario 4: the limit, existence and read access are enforced.
1061 let repo = fresh_repo(s, owner, "assign-limit").await;1000 let repo = fresh_repo(s, owner, "assign-limit").await;
1062 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();1001 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();
1063 let mut usernames = Vec::new();1002 let mut usernames = Vec::new();
@@ -1090,7 +1029,6 @@ mod tests {
1090 "limit: unknown user refused"1029 "limit: unknown user refused"
1091 );1030 );
1092 1031
1093- // Bob has no role on a private repo, so he cannot be assigned there.
1094 let secret = s1032 let secret = s
1095 .create_repo(owner, "assign-secret", "", Visibility::Private, "main")1033 .create_repo(owner, "assign-secret", "", Visibility::Private, "main")
1096 .await1034 .await
@@ -1117,14 +1055,12 @@ mod tests {
1117 );1055 );
1118 }1056 }
1119 1057
1120- // Milestones: creating, listing, updating, linking to issues and deleting.
1121 #[tokio::test]1058 #[tokio::test]
1122 async fn milestone_rules_hold_in_each_scenario() {1059 async fn milestone_rules_hold_in_each_scenario() {
1123 let fx = fixture().await;1060 let fx = fixture().await;
1124 let s = &fx.store;1061 let s = &fx.store;
1125 let owner = &fx.tahinli.id;1062 let owner = &fx.tahinli.id;
1126 1063
1127- // Scenario 1: dates are validated, titles unique, counts shown in one listing.
1128 let repo = fresh_repo(s, owner, "milestones").await;1064 let repo = fresh_repo(s, owner, "milestones").await;
1129 let other = fresh_repo(s, owner, "milestones-other").await;1065 let other = fresh_repo(s, owner, "milestones-other").await;
1130 let v1 = s1066 let v1 = s
@@ -1207,7 +1143,6 @@ mod tests {
1207 "lookup: other repo finds nothing"1143 "lookup: other repo finds nothing"
1208 );1144 );
1209 1145
1210- // Scenario 2: updates set and clear the closed stamp and stay scoped.
1211 let repo = fresh_repo(s, owner, "milestone-update").await;1146 let repo = fresh_repo(s, owner, "milestone-update").await;
1212 let other = fresh_repo(s, owner, "milestone-update-other").await;1147 let other = fresh_repo(s, owner, "milestone-update-other").await;
1213 let v1 = s1148 let v1 = s
@@ -1242,7 +1177,6 @@ mod tests {
1242 );1177 );
1243 assert!(reopened.closed_at.is_none(), "update: closed stamp cleared");1178 assert!(reopened.closed_at.is_none(), "update: closed stamp cleared");
1244 1179
1245- // Scenario 3: an issue takes only milestones of its own repo and records changes.
1246 let repo = fresh_repo(s, owner, "issue-milestone").await;1180 let repo = fresh_repo(s, owner, "issue-milestone").await;
1247 let other = fresh_repo(s, owner, "issue-milestone-other").await;1181 let other = fresh_repo(s, owner, "issue-milestone-other").await;
1248 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();1182 let issue = s.create_issue(&repo, owner, "t", "").await.unwrap();
@@ -1296,7 +1230,6 @@ mod tests {
1296 "issue milestone: v2 recorded"1230 "issue milestone: v2 recorded"
1297 );1231 );
1298 1232
1299- // Clearing again is a no-op.
1300 s.set_issue_milestone(&issue.id, owner, None).await.unwrap();1233 s.set_issue_milestone(&issue.id, owner, None).await.unwrap();
1301 let events = s.list_events(&issue.id).await.unwrap();1234 let events = s.list_events(&issue.id).await.unwrap();
1302 assert_eq!(1235 assert_eq!(
@@ -1314,7 +1247,6 @@ mod tests {
1314 "issue milestone: none stored"1247 "issue milestone: none stored"
1315 );1248 );
1316 1249
1317- // Scenario 4: deleting a milestone clears issue links and is scoped.
1318 let repo = fresh_repo(s, owner, "milestone-delete").await;1250 let repo = fresh_repo(s, owner, "milestone-delete").await;
1319 let other = fresh_repo(s, owner, "milestone-delete-other").await;1251 let other = fresh_repo(s, owner, "milestone-delete-other").await;
1320 let v1 = s.create_milestone(&repo, "v1", "", None).await.unwrap();1252 let v1 = s.create_milestone(&repo, "v1", "", None).await.unwrap();
crates/forge-core/src/store/lfs.rsmodified+0 -8
@@ -1,12 +1,8 @@
1-//! Git LFS object links: which repo holds which content-addressed object. The bytes are stored on
2-//! disk by forge-web (`data_dir/lfs`); this module only records the per-repo links.
3-
4 use super::{Store, col_int, db_err, fetch_opt};1 use super::{Store, col_int, db_err, fetch_opt};
5 use crate::error::{Error, Result};2 use crate::error::{Error, Result};
6 use crate::time::now_stamp;3 use crate::time::now_stamp;
7 4
8 impl Store {5 impl Store {
9- /// Links `oid` (of `size` bytes) to `repo_id`. Idempotent: an existing link is kept as it is.
10 pub async fn insert_lfs_object(&self, repo_id: &str, oid: &str, size: u64) -> Result<()> {6 pub async fn insert_lfs_object(&self, repo_id: &str, oid: &str, size: u64) -> Result<()> {
11 let size =7 let size =
12 i64::try_from(size).map_err(|_| Error::Invalid("the object is too large".into()))?;8 i64::try_from(size).map_err(|_| Error::Invalid("the object is too large".into()))?;
@@ -21,7 +17,6 @@ impl Store {
21 Ok(())17 Ok(())
22 }18 }
23 19
24- /// The size of `oid` in `repo_id`, or `None` when the repo does not link that object.
25 pub async fn lfs_object_size(&self, repo_id: &str, oid: &str) -> Result<Option<u64>> {20 pub async fn lfs_object_size(&self, repo_id: &str, oid: &str) -> Result<Option<u64>> {
26 let conn = self.read_conn().await;21 let conn = self.read_conn().await;
27 let size = fetch_opt(22 let size = fetch_opt(
@@ -37,7 +32,6 @@ impl Store {
37 .transpose()32 .transpose()
38 }33 }
39 34
40- /// Whether any repo links `oid`. Used by `admin lfs-gc`.
41 pub async fn lfs_oid_is_linked(&self, oid: &str) -> Result<bool> {35 pub async fn lfs_oid_is_linked(&self, oid: &str) -> Result<bool> {
42 let conn = self.read_conn().await;36 let conn = self.read_conn().await;
43 let found = fetch_opt(37 let found = fetch_opt(
@@ -71,8 +65,6 @@ mod tests {
71 (store, repo.id, user.id)65 (store, repo.id, user.id)
72 }66 }
73 67
74- // One store serves both checks. Deleting a repo runs first, so the link
75- // check below starts from a store with no links at all.
76 #[tokio::test]68 #[tokio::test]
77 async fn lfs_links_per_repo_idempotent_and_removed_with_repo() {69 async fn lfs_links_per_repo_idempotent_and_removed_with_repo() {
78 let dir = tempfile::tempdir().unwrap();70 let dir = tempfile::tempdir().unwrap();
crates/forge-core/src/store/mail.rsmodified+0 -36
@@ -1,7 +1,3 @@
1-//! Mail storage: the singleton SMTP settings (password sealed with the instance key) and the
2-//! outbox. The outbox follows iz's shape: an idempotency key, a lease, and a retry schedule.
3-//! Timestamps are fixed-width UTC stamps, so `next_attempt_at <= now` is a text comparison.
4-
5 use turso::{Row, Value};1 use turso::{Row, Value};
6 2
7 use super::{3 use super::{
@@ -21,7 +17,6 @@ const OUTBOX_COLS: &str = "id, idem_key, to_addr, subject, body_text, created_at
21 next_attempt_at, sent_at, last_error, message_id, in_reply_to, kind, \17 next_attempt_at, sent_at, last_error, message_id, in_reply_to, kind, \
22 user_id, lease_until, discarded_at";18 user_id, lease_until, discarded_at";
23 19
24-/// The SQL condition that selects the rows in `state`. It takes `?1`, the current stamp.
25 fn state_clause(state: MailState) -> &'static str {20 fn state_clause(state: MailState) -> &'static str {
26 match state {21 match state {
27 MailState::Sent => "sent_at IS NOT NULL",22 MailState::Sent => "sent_at IS NOT NULL",
@@ -84,7 +79,6 @@ fn map_outbox(row: &Row) -> Result<OutboxEntry> {
84 }79 }
85 80
86 impl Store {81 impl Store {
87- /// The SMTP settings. The row always exists (the migration inserts it).
88 pub async fn mail_settings(&self) -> Result<MailSettings> {82 pub async fn mail_settings(&self) -> Result<MailSettings> {
89 let conn = self.read_conn().await;83 let conn = self.read_conn().await;
90 fetch_opt(84 fetch_opt(
@@ -97,8 +91,6 @@ impl Store {
97 .ok_or_else(missing_row)91 .ok_or_else(missing_row)
98 }92 }
99 93
100- /// Stores new SMTP settings. A `password` of `None` keeps the stored one. The password is
101- /// sealed with the instance key; without that key the write is refused.
102 pub async fn update_mail_settings(94 pub async fn update_mail_settings(
103 &self,95 &self,
104 update: &MailSettingsUpdate<'_>,96 update: &MailSettingsUpdate<'_>,
@@ -135,8 +127,6 @@ impl Store {
135 self.mail_settings().await127 self.mail_settings().await
136 }128 }
137 129
138- /// The decrypted SMTP password, or `None` when none is stored. A stored password that cannot
139- /// be opened is an error, not a silent "no password".
140 pub async fn mail_password(&self) -> Result<Option<MailPassword>> {130 pub async fn mail_password(&self) -> Result<Option<MailPassword>> {
141 let sealed = {131 let sealed = {
142 let conn = self.read_conn().await;132 let conn = self.read_conn().await;
@@ -165,8 +155,6 @@ impl Store {
165 Ok(Some(MailPassword::new(plain)))155 Ok(Some(MailPassword::new(plain)))
166 }156 }
167 157
168- /// Queues a message. Returns `false` when a row with the same `idem_key` already exists, so
169- /// a repeated call (a retried request, a second pass over the same event) sends nothing twice.
170 pub async fn enqueue_mail(&self, idem_key: &str, mail: &OutgoingMail) -> Result<bool> {158 pub async fn enqueue_mail(&self, idem_key: &str, mail: &OutgoingMail) -> Result<bool> {
171 if idem_key.is_empty() || idem_key.len() > 200 {159 if idem_key.is_empty() || idem_key.len() > 200 {
172 return Err(Error::Invalid(160 return Err(Error::Invalid(
@@ -200,8 +188,6 @@ impl Store {
200 Ok(inserted > 0)188 Ok(inserted > 0)
201 }189 }
202 190
203- /// Leases up to `limit` due messages until `lease_until`. A leased row is skipped by other
204- /// passes until the lease runs out. Select and lease happen in one transaction.
205 pub async fn lease_mail(191 pub async fn lease_mail(
206 &self,192 &self,
207 now: &str,193 now: &str,
@@ -234,7 +220,6 @@ impl Store {
234 Ok(due)220 Ok(due)
235 }221 }
236 222
237- /// Marks a message as sent and clears its lease.
238 pub async fn mark_mail_sent(&self, id: &str, now: &str) -> Result<()> {223 pub async fn mark_mail_sent(&self, id: &str, now: &str) -> Result<()> {
239 let conn = self.inner.conn.lock().await;224 let conn = self.inner.conn.lock().await;
240 conn.execute(225 conn.execute(
@@ -247,7 +232,6 @@ impl Store {
247 Ok(())232 Ok(())
248 }233 }
249 234
250- /// Records a failed try. `next_attempt_at` of `None` gives up on the message.
251 pub async fn mark_mail_failed(235 pub async fn mark_mail_failed(
252 &self,236 &self,
253 id: &str,237 id: &str,
@@ -269,7 +253,6 @@ impl Store {
269 Ok(())253 Ok(())
270 }254 }
271 255
272- /// The earliest scheduled try among unsent messages, if any.
273 pub async fn next_mail_due(&self) -> Result<Option<String>> {256 pub async fn next_mail_due(&self) -> Result<Option<String>> {
274 let conn = self.read_conn().await;257 let conn = self.read_conn().await;
275 fetch_opt(258 fetch_opt(
@@ -283,8 +266,6 @@ impl Store {
283 .map(Option::flatten)266 .map(Option::flatten)
284 }267 }
285 268
286- /// Outbox rows in `state` (or every row when `None`), newest first. `now` decides the
287- /// states that depend on the clock (sending, and the queued and retrying split).
288 pub async fn list_mail(269 pub async fn list_mail(
289 &self,270 &self,
290 state: Option<MailState>,271 state: Option<MailState>,
@@ -305,7 +286,6 @@ impl Store {
305 .await286 .await
306 }287 }
307 288
308- /// How many outbox rows stand in each state at `now`, in `MailState::ALL` order.
309 pub async fn mail_state_counts(&self, now: &str) -> Result<Vec<(MailState, u32)>> {289 pub async fn mail_state_counts(&self, now: &str) -> Result<Vec<(MailState, u32)>> {
310 let conn = self.read_conn().await;290 let conn = self.read_conn().await;
311 let columns = MailState::ALL291 let columns = MailState::ALL
@@ -326,8 +306,6 @@ impl Store {
326 Ok(counts.unwrap_or_default())306 Ok(counts.unwrap_or_default())
327 }307 }
328 308
329- /// Gives a failed message a fresh set of tries, due at `now`. Returns `false` when the row is
330- /// not failed (it was sent, discarded, or is still scheduled).
331 pub async fn retry_mail(&self, id: &str, now: &str) -> Result<bool> {309 pub async fn retry_mail(&self, id: &str, now: &str) -> Result<bool> {
332 let conn = self.inner.conn.lock().await;310 let conn = self.inner.conn.lock().await;
333 let changed = conn311 let changed = conn
@@ -342,8 +320,6 @@ impl Store {
342 Ok(changed > 0)320 Ok(changed > 0)
343 }321 }
344 322
345- /// Gives up on a failed message for good, keeping its row and last error. Returns `false`
346- /// when the row is not failed.
347 pub async fn discard_mail(&self, id: &str, now: &str) -> Result<bool> {323 pub async fn discard_mail(&self, id: &str, now: &str) -> Result<bool> {
348 let conn = self.inner.conn.lock().await;324 let conn = self.inner.conn.lock().await;
349 let changed = conn325 let changed = conn
@@ -357,9 +333,6 @@ impl Store {
357 Ok(changed > 0)333 Ok(changed > 0)
358 }334 }
359 335
360- /// Clears the leases of unsent rows and returns how many were cleared. Run once at boot: a
361- /// lease left by a process that stopped mid-pass would hold its row until the lease ran out,
362- /// and the row is due again as soon as it is released.
363 pub async fn release_mail_leases(&self) -> Result<u64> {336 pub async fn release_mail_leases(&self) -> Result<u64> {
364 let conn = self.inner.conn.lock().await;337 let conn = self.inner.conn.lock().await;
365 conn.execute(338 conn.execute(
@@ -371,8 +344,6 @@ impl Store {
371 .map_err(db_err)344 .map_err(db_err)
372 }345 }
373 346
374- /// The newest message of `kind` sent about `user_id`, with its state now. `None` when no such
375- /// message was queued.
376 pub async fn latest_mail_for(347 pub async fn latest_mail_for(
377 &self,348 &self,
378 user_id: &str,349 user_id: &str,
@@ -399,7 +370,6 @@ impl Store {
399 }))370 }))
400 }371 }
401 372
402- /// The newest outbox rows, newest first.
403 pub async fn recent_mail(&self, limit: u32) -> Result<Vec<OutboxEntry>> {373 pub async fn recent_mail(&self, limit: u32) -> Result<Vec<OutboxEntry>> {
404 let conn = self.read_conn().await;374 let conn = self.read_conn().await;
405 fetch_all(375 fetch_all(
@@ -458,7 +428,6 @@ mod tests {
458 }428 }
459 }429 }
460 430
461- /// A repeated key queues once, and bad recipients or an empty key are refused.
462 #[tokio::test]431 #[tokio::test]
463 async fn enqueue_dedupes_by_key_and_refuses_bad_input() {432 async fn enqueue_dedupes_by_key_and_refuses_bad_input() {
464 let (_dir, store) = store_with_key().await;433 let (_dir, store) = store_with_key().await;
@@ -482,7 +451,6 @@ mod tests {
482 );451 );
483 assert_eq!(store.recent_mail(10).await.expect("rows").len(), 2);452 assert_eq!(store.recent_mail(10).await.expect("rows").len(), 2);
484 453
485- // a bad recipient and an empty key are refused
486 assert!(454 assert!(
487 store455 store
488 .enqueue_mail("k", &mail("not an address"))456 .enqueue_mail("k", &mail("not an address"))
@@ -602,7 +570,6 @@ mod tests {
602 assert_eq!(store.next_mail_due().await.expect("none"), None);570 assert_eq!(store.next_mail_due().await.expect("none"), None);
603 }571 }
604 572
605- /// The password is sealed at rest and round-trips, and saving without one keeps it.
606 #[tokio::test]573 #[tokio::test]
607 async fn mail_password_is_sealed_and_kept() {574 async fn mail_password_is_sealed_and_kept() {
608 let (_dir, store) = store_with_key().await;575 let (_dir, store) = store_with_key().await;
@@ -625,7 +592,6 @@ mod tests {
625 Some("s3cret-smtp-pw".to_owned())592 Some("s3cret-smtp-pw".to_owned())
626 );593 );
627 594
628- // saving without a password keeps the stored one
629 store595 store
630 .update_mail_settings(&settings(Some("first-pw")))596 .update_mail_settings(&settings(Some("first-pw")))
631 .await597 .await
@@ -644,7 +610,6 @@ mod tests {
644 Some("first-pw".to_owned())610 Some("first-pw".to_owned())
645 );611 );
646 612
647- // The column holds ciphertext, not the password.
648 let conn = store.inner.conn.lock().await;613 let conn = store.inner.conn.lock().await;
649 let mut rows = conn614 let mut rows = conn
650 .query("SELECT password_sealed FROM mail_settings WHERE id = 1", ())615 .query("SELECT password_sealed FROM mail_settings WHERE id = 1", ())
@@ -667,7 +632,6 @@ mod tests {
667 store.update_mail_settings(&settings(Some("pw"))).await,632 store.update_mail_settings(&settings(Some("pw"))).await,
668 Err(Error::Crypto(_))633 Err(Error::Crypto(_))
669 ));634 ));
670- // Without a password, no key is needed.
671 assert!(store.update_mail_settings(&settings(None)).await.is_ok());635 assert!(store.update_mail_settings(&settings(None)).await.is_ok());
672 }636 }
673 637
crates/forge-core/src/store/merge_queue.rsmodified+0 -18
@@ -1,6 +1,3 @@
1-//! Merge queue rows. The engine that moves entries along lives in forge-web (`merge_queue`); every
2-//! transition here is a conditional write, so two events that race on one entry cannot both win.
3-
4 use turso::Value;1 use turso::Value;
5 2
6 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};3 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
@@ -12,12 +9,9 @@ use crate::time::now_stamp;
12 const QUEUE_COLS: &str = "id, repo_id, branch, issue_id, pull_number, merge_style, state, seq, \9 const QUEUE_COLS: &str = "id, repo_id, branch, issue_id, pull_number, merge_style, state, seq, \
13 enqueued_by, enqueued_at, updated_at, finished_at, reason, base_oid, tested_oid, test_ref, run_id";10 enqueued_by, enqueued_at, updated_at, finished_at, reason, base_oid, tested_oid, test_ref, run_id";
14 11
15-/// Finished entries shown in the queue history.
16 const HISTORY_LIMIT: i64 = 30;12 const HISTORY_LIMIT: i64 = 30;
17 13
18 impl Store {14 impl Store {
19- /// Adds a pull request to the end of the branch queue. Fails with `Conflict` when the pull
20- /// request already waits in a queue.
21 pub async fn enqueue_pull(15 pub async fn enqueue_pull(
22 &self,16 &self,
23 repo_id: &str,17 repo_id: &str,
@@ -81,7 +75,6 @@ impl Store {
81 finish(tx, outcome).await75 finish(tx, outcome).await
82 }76 }
83 77
84- /// The waiting entries of one branch, in queue order (the first is the head).
85 pub async fn queue_for_branch(&self, repo_id: &str, branch: &str) -> Result<Vec<QueueEntry>> {78 pub async fn queue_for_branch(&self, repo_id: &str, branch: &str) -> Result<Vec<QueueEntry>> {
86 let conn = self.read_conn().await;79 let conn = self.read_conn().await;
87 fetch_all(80 fetch_all(
@@ -96,7 +89,6 @@ impl Store {
96 .await89 .await
97 }90 }
98 91
99- /// The waiting entry of a pull request, if it waits in a queue.
100 pub async fn queue_entry_for_pull(&self, issue_id: &str) -> Result<Option<QueueEntry>> {92 pub async fn queue_entry_for_pull(&self, issue_id: &str) -> Result<Option<QueueEntry>> {
101 let conn = self.read_conn().await;93 let conn = self.read_conn().await;
102 fetch_opt(94 fetch_opt(
@@ -111,8 +103,6 @@ impl Store {
111 .await103 .await
112 }104 }
113 105
114- /// The waiting entries of a repo (all branches, queue order) followed by its most recent
115- /// finished entries.
116 pub async fn queue_overview(&self, repo_id: &str) -> Result<Vec<QueueEntry>> {106 pub async fn queue_overview(&self, repo_id: &str) -> Result<Vec<QueueEntry>> {
117 let conn = self.read_conn().await;107 let conn = self.read_conn().await;
118 let mut out = fetch_all(108 let mut out = fetch_all(
@@ -139,7 +129,6 @@ impl Store {
139 Ok(out)129 Ok(out)
140 }130 }
141 131
142- /// The entries of `repo_id` in `testing` whose candidate is `oid`.
143 pub async fn queue_testing_on(&self, repo_id: &str, oid: &str) -> Result<Vec<QueueEntry>> {132 pub async fn queue_testing_on(&self, repo_id: &str, oid: &str) -> Result<Vec<QueueEntry>> {
144 let conn = self.read_conn().await;133 let conn = self.read_conn().await;
145 fetch_all(134 fetch_all(
@@ -154,8 +143,6 @@ impl Store {
154 .await143 .await
155 }144 }
156 145
157- /// Starts testing `base` plus the pull request as `tested` under `test_ref`. Works from
158- /// `queued` (first start) and `testing` (a rebuild). Returns false when the entry has moved on.
159 pub async fn queue_set_testing(146 pub async fn queue_set_testing(
160 &self,147 &self,
161 id: &str,148 id: &str,
@@ -177,7 +164,6 @@ impl Store {
177 .await164 .await
178 }165 }
179 166
180- /// Moves a tested entry to `merging`. False when another event already took it.
181 pub async fn queue_set_merging(&self, id: &str) -> Result<bool> {167 pub async fn queue_set_merging(&self, id: &str) -> Result<bool> {
182 self.queue_update(168 self.queue_update(
183 "UPDATE merge_queue SET state = 'merging', updated_at = ?2 WHERE id = ?1 AND state = 'testing'",169 "UPDATE merge_queue SET state = 'merging', updated_at = ?2 WHERE id = ?1 AND state = 'testing'",
@@ -186,7 +172,6 @@ impl Store {
186 .await172 .await
187 }173 }
188 174
189- /// Puts a `merging` entry back at the head of the queue, after the target moved under it.
190 pub async fn queue_set_queued(&self, id: &str) -> Result<bool> {175 pub async fn queue_set_queued(&self, id: &str) -> Result<bool> {
191 self.queue_update(176 self.queue_update(
192 "UPDATE merge_queue SET state = 'queued', base_oid = NULL, tested_oid = NULL, test_ref = NULL, \177 "UPDATE merge_queue SET state = 'queued', base_oid = NULL, tested_oid = NULL, test_ref = NULL, \
@@ -196,7 +181,6 @@ impl Store {
196 .await181 .await
197 }182 }
198 183
199- /// Ends a waiting entry as `failed` or `removed` with `reason`. False if it already finished.
200 pub async fn queue_finish(&self, id: &str, state: QueueState, reason: &str) -> Result<bool> {184 pub async fn queue_finish(&self, id: &str, state: QueueState, reason: &str) -> Result<bool> {
201 let now = now_stamp();185 let now = now_stamp();
202 self.queue_update(186 self.queue_update(
@@ -212,7 +196,6 @@ impl Store {
212 .await196 .await
213 }197 }
214 198
215- /// One entry by id.
216 pub async fn queue_entry(&self, id: &str) -> Result<Option<QueueEntry>> {199 pub async fn queue_entry(&self, id: &str) -> Result<Option<QueueEntry>> {
217 let conn = self.read_conn().await;200 let conn = self.read_conn().await;
218 fetch_opt(201 fetch_opt(
@@ -231,7 +214,6 @@ impl Store {
231 }214 }
232 }215 }
233 216
234-/// Reads `QUEUE_COLS`.
235 fn map_entry(row: &turso::Row) -> Result<QueueEntry> {217 fn map_entry(row: &turso::Row) -> Result<QueueEntry> {
236 Ok(QueueEntry {218 Ok(QueueEntry {
237 id: col_text(row, 0)?,219 id: col_text(row, 0)?,
crates/forge-core/src/store/migrate.rsmodified+0 -6
@@ -1,11 +1,8 @@
1-//! Migration runner. Applied versions are recorded in the `schema_migrations` table.
2-
3 use turso::Connection;1 use turso::Connection;
4 2
5 use crate::error::{Error, Result};3 use crate::error::{Error, Result};
6 use crate::time::now_stamp;4 use crate::time::now_stamp;
7 5
8-/// `(version, sql)` in ascending order.
9 pub const MIGRATIONS: &[(u32, &str)] = &[6 pub const MIGRATIONS: &[(u32, &str)] = &[
10 (1, include_str!("../../migrations/0001_init.sql")),7 (1, include_str!("../../migrations/0001_init.sql")),
11 (2, include_str!("../../migrations/0002_profile.sql")),8 (2, include_str!("../../migrations/0002_profile.sql")),
@@ -131,7 +128,6 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
131 ),128 ),
132 ];129 ];
133 130
134-/// The highest migration version this binary knows about.
135 pub fn latest_schema_version() -> u32 {131 pub fn latest_schema_version() -> u32 {
136 MIGRATIONS.last().map_or(0, |m| m.0)132 MIGRATIONS.last().map_or(0, |m| m.0)
137 }133 }
@@ -140,8 +136,6 @@ fn migration_err(e: turso::Error) -> Error {
140 Error::Migration(e.to_string())136 Error::Migration(e.to_string())
141 }137 }
142 138
143-/// Applies every migration whose version is not yet recorded. Each migration runs in its own
144-/// transaction together with its `schema_migrations` row, so a failure leaves nothing behind.
145 pub async fn migrate(conn: &Connection) -> Result<()> {139 pub async fn migrate(conn: &Connection) -> Result<()> {
146 conn.execute_batch(140 conn.execute_batch(
147 "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",141 "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",
crates/forge-core/src/store/mirrors.rsmodified+0 -35
@@ -1,9 +1,3 @@
1-//! Mirror storage: pull and push mirrors of a repo, and their sealed secrets.
2-//!
3-//! The store seals secrets with the instance key set by `Store::set_secret_key`, the same way
4-//! webhook secrets are sealed. `mirror_secret` is the only read that returns plaintext.
5-//! Timestamps are RFC 3339 UTC stamps, so `next_sync_at <= now` is a text comparison.
6-
7 use turso::{Row, Value};1 use turso::{Row, Value};
8 2
9 use super::{3 use super::{
@@ -17,7 +11,6 @@ use crate::mirrors::{
17 use crate::secret;11 use crate::secret;
18 use crate::time::now_stamp;12 use crate::time::now_stamp;
19 13
20-/// Largest page `due_mirrors` returns, whatever the caller asks for.
21 const MAX_PAGE: u32 = 200;14 const MAX_PAGE: u32 = 200;
22 15
23 const MIRROR_COLS: &str = "id, repo_id, direction, url, username, secret_sealed IS NOT NULL, \16 const MIRROR_COLS: &str = "id, repo_id, direction, url, username, secret_sealed IS NOT NULL, \
@@ -44,7 +37,6 @@ fn map_mirror(row: &Row) -> Result<Mirror> {
44 })37 })
45 }38 }
46 39
47-/// Rejects an interval that is neither `0` (manual only) nor at least the minimum.
48 fn validate_interval(minutes: u32) -> Result<()> {40 fn validate_interval(minutes: u32) -> Result<()> {
49 if minutes != 0 && minutes < MIN_INTERVAL_MINUTES {41 if minutes != 0 && minutes < MIN_INTERVAL_MINUTES {
50 return Err(Error::Invalid(format!(42 return Err(Error::Invalid(format!(
@@ -55,13 +47,10 @@ fn validate_interval(minutes: u32) -> Result<()> {
55 }47 }
56 48
57 impl Store {49 impl Store {
58- /// Seals a plaintext mirror secret with the instance key.
59 fn seal_mirror_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {50 fn seal_mirror_secret(&self, plain: &[u8]) -> Result<Vec<u8>> {
60 Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())51 Ok(secret::seal(self.secret_key()?, plain)?.into_bytes())
61 }52 }
62 53
63- /// Creates a mirror. The repo has at most one pull mirror (`Conflict` for a second) and at
64- /// most [`MAX_PUSH_MIRRORS`] push mirrors (`Invalid` beyond that). The new mirror is due now.
65 pub async fn create_mirror(&self, new: &NewMirror<'_>) -> Result<Mirror> {54 pub async fn create_mirror(&self, new: &NewMirror<'_>) -> Result<Mirror> {
66 validate_interval(new.interval_minutes)?;55 validate_interval(new.interval_minutes)?;
67 let sealed = new.secret.map(|s| self.seal_mirror_secret(s)).transpose()?;56 let sealed = new.secret.map(|s| self.seal_mirror_secret(s)).transpose()?;
@@ -113,7 +102,6 @@ impl Store {
113 self.mirror(&id).await?.ok_or(Error::NotFound)102 self.mirror(&id).await?.ok_or(Error::NotFound)
114 }103 }
115 104
116- /// The mirrors of a repo, pull first, then by creation time.
117 pub async fn list_mirrors(&self, repo_id: &str) -> Result<Vec<Mirror>> {105 pub async fn list_mirrors(&self, repo_id: &str) -> Result<Vec<Mirror>> {
118 let conn = self.read_conn().await;106 let conn = self.read_conn().await;
119 fetch_all(107 fetch_all(
@@ -128,7 +116,6 @@ impl Store {
128 .await116 .await
129 }117 }
130 118
131- /// One mirror, or `None`. The secret is not included.
132 pub async fn mirror(&self, id: &str) -> Result<Option<Mirror>> {119 pub async fn mirror(&self, id: &str) -> Result<Option<Mirror>> {
133 let conn = self.read_conn().await;120 let conn = self.read_conn().await;
134 fetch_opt(121 fetch_opt(
@@ -140,7 +127,6 @@ impl Store {
140 .await127 .await
141 }128 }
142 129
143- /// The pull mirror of a repo, or `None`.
144 pub async fn pull_mirror(&self, repo_id: &str) -> Result<Option<Mirror>> {130 pub async fn pull_mirror(&self, repo_id: &str) -> Result<Option<Mirror>> {
145 let conn = self.read_conn().await;131 let conn = self.read_conn().await;
146 fetch_opt(132 fetch_opt(
@@ -154,8 +140,6 @@ impl Store {
154 .await140 .await
155 }141 }
156 142
157- /// Replaces a mirror's URL, username, interval and enabled flag. `secret` decides what
158- /// happens to the stored secret. `NotFound` if the mirror does not exist.
159 pub async fn update_mirror(143 pub async fn update_mirror(
160 &self,144 &self,
161 id: &str,145 id: &str,
@@ -205,7 +189,6 @@ impl Store {
205 Ok(())189 Ok(())
206 }190 }
207 191
208- /// Deletes a mirror. `NotFound` if it does not exist.
209 pub async fn delete_mirror(&self, id: &str) -> Result<()> {192 pub async fn delete_mirror(&self, id: &str) -> Result<()> {
210 let conn = self.inner.conn.lock().await;193 let conn = self.inner.conn.lock().await;
211 let n = conn194 let n = conn
@@ -218,8 +201,6 @@ impl Store {
218 Ok(())201 Ok(())
219 }202 }
220 203
221- /// The plaintext secret of a mirror, opened with the instance key. `None` when the mirror
222- /// is gone or has no secret. Only the sync worker should call this.
223 pub async fn mirror_secret(&self, id: &str) -> Result<Option<Vec<u8>>> {204 pub async fn mirror_secret(&self, id: &str) -> Result<Option<Vec<u8>>> {
224 let sealed = {205 let sealed = {
225 let conn = self.read_conn().await;206 let conn = self.read_conn().await;
@@ -244,7 +225,6 @@ impl Store {
244 Ok(Some(secret::open(self.secret_key()?, &sealed)?))225 Ok(Some(secret::open(self.secret_key()?, &sealed)?))
245 }226 }
246 227
247- /// Enabled mirrors due at or before `now`, earliest first, at most `limit` (capped at 200).
248 pub async fn due_mirrors(&self, now: &str, limit: u32) -> Result<Vec<Mirror>> {228 pub async fn due_mirrors(&self, now: &str, limit: u32) -> Result<Vec<Mirror>> {
249 let conn = self.inner.conn.lock().await;229 let conn = self.inner.conn.lock().await;
250 fetch_all(230 fetch_all(
@@ -259,7 +239,6 @@ impl Store {
259 .await239 .await
260 }240 }
261 241
262- /// The earliest `next_sync_at` among enabled mirrors, or `None` when none is enabled.
263 pub async fn next_mirror_due(&self) -> Result<Option<String>> {242 pub async fn next_mirror_due(&self) -> Result<Option<String>> {
264 let conn = self.read_conn().await;243 let conn = self.read_conn().await;
265 fetch_opt(244 fetch_opt(
@@ -272,7 +251,6 @@ impl Store {
272 .map(Option::flatten)251 .map(Option::flatten)
273 }252 }
274 253
275- /// Sets when a mirror is next due. "Sync now" passes the current time.
276 pub async fn schedule_mirror(&self, id: &str, next_sync_at: &str) -> Result<()> {254 pub async fn schedule_mirror(&self, id: &str, next_sync_at: &str) -> Result<()> {
277 let conn = self.inner.conn.lock().await;255 let conn = self.inner.conn.lock().await;
278 let n = conn256 let n = conn
@@ -288,8 +266,6 @@ impl Store {
288 Ok(())266 Ok(())
289 }267 }
290 268
291- /// Records the outcome of a sync run: stamps `last_sync_at` with now, sets `last_ok` and
292- /// `last_error`, and schedules the next run. `NotFound` if the mirror does not exist.
293 pub async fn record_mirror_result(269 pub async fn record_mirror_result(
294 &self,270 &self,
295 id: &str,271 id: &str,
@@ -369,14 +345,10 @@ mod tests {
369 .unwrap()345 .unwrap()
370 }346 }
371 347
372- // Pull and push rules, interval checks, the result/delete path, repo
373- // deletion and the push-mirror cap share one store. Each block works on
374- // its own repo so the cases cannot interfere with each other.
375 #[tokio::test]348 #[tokio::test]
376 async fn mirror_rules_and_lifecycle_per_repo() {349 async fn mirror_rules_and_lifecycle_per_repo() {
377 let (store, tahinli, repo, _dir) = setup().await;350 let (store, tahinli, repo, _dir) = setup().await;
378 351
379- // One pull mirror per repo; push mirrors are not limited by that slot.
380 let first = store352 let first = store
381 .create_mirror(&pull(&repo, "https://a.example/x.git"))353 .create_mirror(&pull(&repo, "https://a.example/x.git"))
382 .await354 .await
@@ -405,7 +377,6 @@ mod tests {
405 "one pull plus one push"377 "one pull plus one push"
406 );378 );
407 379
408- // Intervals: 5 minutes is too short, 0 means manual sync only.
409 let interval_repo = add_repo(&store, &tahinli, "interval").await;380 let interval_repo = add_repo(&store, &tahinli, "interval").await;
410 let too_short = store381 let too_short = store
411 .create_mirror(&NewMirror {382 .create_mirror(&NewMirror {
@@ -426,7 +397,6 @@ mod tests {
426 .unwrap();397 .unwrap();
427 assert_eq!(manual.interval_minutes, 0, "manual interval kept");398 assert_eq!(manual.interval_minutes, 0, "manual interval kept");
428 399
429- // Recording a result, then deleting the mirror.
430 let record_repo = add_repo(&store, &tahinli, "record").await;400 let record_repo = add_repo(&store, &tahinli, "record").await;
431 let m = store401 let m = store
432 .create_mirror(&pull(&record_repo, "https://a.example/x.git"))402 .create_mirror(&pull(&record_repo, "https://a.example/x.git"))
@@ -452,7 +422,6 @@ mod tests {
452 "deleting twice is NotFound"422 "deleting twice is NotFound"
453 );423 );
454 424
455- // Deleting the repo removes its mirrors.
456 let gone = add_repo(&store, &tahinli, "gone").await;425 let gone = add_repo(&store, &tahinli, "gone").await;
457 let g = store426 let g = store
458 .create_mirror(&pull(&gone, "https://a.example/x.git"))427 .create_mirror(&pull(&gone, "https://a.example/x.git"))
@@ -464,7 +433,6 @@ mod tests {
464 "delete_repo removes mirrors"433 "delete_repo removes mirrors"
465 );434 );
466 435
467- // The push cap: ten per repo, the eleventh is refused.
468 let ten = add_repo(&store, &tahinli, "ten").await;436 let ten = add_repo(&store, &tahinli, "ten").await;
469 for n in 0..MAX_PUSH_MIRRORS {437 for n in 0..MAX_PUSH_MIRRORS {
470 store438 store
@@ -505,7 +473,6 @@ mod tests {
505 Some(&plain[..])473 Some(&plain[..])
506 );474 );
507 475
508- // The stored bytes are the sealed form, not the plaintext.
509 {476 {
510 let conn = store.inner.conn.lock().await;477 let conn = store.inner.conn.lock().await;
511 let mut rows = conn478 let mut rows = conn
@@ -523,7 +490,6 @@ mod tests {
523 assert!(!raw.windows(plain.len()).any(|w| w == plain));490 assert!(!raw.windows(plain.len()).any(|w| w == plain));
524 }491 }
525 492
526- // Keep leaves it, Set replaces it, Clear removes it.
527 store493 store
528 .update_mirror(494 .update_mirror(
529 &created.id,495 &created.id,
@@ -654,7 +620,6 @@ mod tests {
654 assert_eq!(limited.len(), 1);620 assert_eq!(limited.len(), 1);
655 assert_eq!(limited[0].id, early.id);621 assert_eq!(limited[0].id, early.id);
656 622
657- // "Sync now" makes the future one due.
658 store.schedule_mirror(&future.id, &now).await.unwrap();623 store.schedule_mirror(&future.id, &now).await.unwrap();
659 assert_eq!(store.due_mirrors(&now, 10).await.unwrap().len(), 3);624 assert_eq!(store.due_mirrors(&now, 10).await.unwrap().len(), 3);
660 }625 }
crates/forge-core/src/store/mod.rsmodified+0 -128
@@ -1,5 +1,3 @@
1-//! Turso-backed storage. All metadata lives here.
2-
3 pub mod account_tokens;1 pub mod account_tokens;
4 pub mod admin_alerts;2 pub mod admin_alerts;
5 pub mod advisories;3 pub mod advisories;
@@ -73,17 +71,11 @@ use crate::time::now_stamp;
73 const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);71 const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);
74 72
75 const IN_CHUNK: usize = 500;73 const IN_CHUNK: usize = 500;
76-/// Longest accepted `about` text, in characters.
77 pub const MAX_ABOUT_CHARS: usize = 2000;74 pub const MAX_ABOUT_CHARS: usize = 2000;
78-/// Longest accepted display name, in characters.
79 pub const MAX_DISPLAY_NAME_CHARS: usize = 80;75 pub const MAX_DISPLAY_NAME_CHARS: usize = 80;
80-/// Most SSH keys one account can have.
81 pub const MAX_SSH_KEYS: i64 = 100;76 pub const MAX_SSH_KEYS: i64 = 100;
82-/// Most access tokens one account can have, expired ones included until deleted.
83 pub const MAX_TOKENS: i64 = 100;77 pub const MAX_TOKENS: i64 = 100;
84 78
85-/// Checks a display name. Surrounding whitespace is trimmed; an empty result means "no name" and
86-/// gives `None`. Control characters are rejected; any other Unicode text is allowed.
87 pub fn validate_display_name(input: &str) -> Result<Option<String>> {79 pub fn validate_display_name(input: &str) -> Result<Option<String>> {
88 let name = input.trim();80 let name = input.trim();
89 if name.is_empty() {81 if name.is_empty() {
@@ -102,34 +94,18 @@ pub fn validate_display_name(input: &str) -> Result<Option<String>> {
102 Ok(Some(name.to_string()))94 Ok(Some(name.to_string()))
103 }95 }
104 96
105-/// Async and `Clone`.
106-///
107-/// Connections: `conn` is the single writer. Every write, every transaction, and every
108-/// read-then-write sequence runs on it behind its tokio mutex, which keeps transactions from
109-/// interleaving. `readers` is a small pool of `query_only` connections on the same database
110-/// (WAL), so pure reads can run in parallel with each other and with the writer.
111-///
112-/// Rule for `read_conn()`:
113-/// - Use it only for a function that is a pure SELECT (one statement, or several SELECTs with
114-/// no writes) and that does not need to see a write made in the same call.
115-/// - Anything inside a transaction, any write, and any read-then-write sequence stays on `conn`.
116-/// - `snapshot.rs` keeps using the writer lock to block writers.
117 #[derive(Clone)]97 #[derive(Clone)]
118 pub struct Store {98 pub struct Store {
119 inner: Arc<Inner>,99 inner: Arc<Inner>,
120 }100 }
121 101
122-/// Number of read-only connections in the pool.
123 const READER_COUNT: usize = 4;102 const READER_COUNT: usize = 4;
124 103
125 struct Inner {104 struct Inner {
126 _db: Database,105 _db: Database,
127 conn: Mutex<Connection>,106 conn: Mutex<Connection>,
128- /// Read-only connections, each with `PRAGMA query_only = 1`. See `Store::read_conn`.
129 readers: Vec<Mutex<Connection>>,107 readers: Vec<Mutex<Connection>>,
130- /// Round-robin start index for `read_conn`.
131 next_reader: AtomicUsize,108 next_reader: AtomicUsize,
132- /// Instance key that seals mirror secrets. Set once at boot by `set_secret_key`.
133 secret_key: std::sync::OnceLock<[u8; 32]>,109 secret_key: std::sync::OnceLock<[u8; 32]>,
134 }110 }
135 111
@@ -145,7 +121,6 @@ const REPO_COLS: &str = "r.id, r.owner_id, u.username, r.name, r.description, r.
145 r.default_branch, r.archived, r.created_at, r.fork_of";121 r.default_branch, r.archived, r.created_at, r.fork_of";
146 122
147 impl Store {123 impl Store {
148- /// WAL, synchronous=FULL, foreign_keys=ON, busy_timeout; runs migrations.
149 pub async fn open(path: &Path) -> Result<Store> {124 pub async fn open(path: &Path) -> Result<Store> {
150 let path_str = path.to_str().ok_or_else(|| {125 let path_str = path.to_str().ok_or_else(|| {
151 Error::Config(format!("database path is not UTF-8: {}", path.display()))126 Error::Config(format!("database path is not UTF-8: {}", path.display()))
@@ -177,9 +152,6 @@ impl Store {
177 })152 })
178 }153 }
179 154
180- /// Returns a read-only pooled connection. Tries each reader with `try_lock`, starting at the
181- /// round-robin index, and falls back to waiting on the round-robin one if all are busy.
182- /// Only for pure SELECT functions. See the rule on [`Store`].
183 pub async fn read_conn(&self) -> MutexGuard<'_, Connection> {155 pub async fn read_conn(&self) -> MutexGuard<'_, Connection> {
184 let len = self.inner.readers.len();156 let len = self.inner.readers.len();
185 let start = self.inner.next_reader.fetch_add(1, Ordering::Relaxed) % len;157 let start = self.inner.next_reader.fetch_add(1, Ordering::Relaxed) % len;
@@ -192,8 +164,6 @@ impl Store {
192 self.inner.readers[start].lock().await164 self.inner.readers[start].lock().await
193 }165 }
194 166
195- /// Sets the instance key that seals mirror secrets. The first key set wins; later calls are
196- /// ignored. Mirror secret operations fail with `Crypto` until a key is set.
197 pub fn set_secret_key(&self, key: [u8; 32]) {167 pub fn set_secret_key(&self, key: [u8; 32]) {
198 let _ = self.inner.secret_key.set(key);168 let _ = self.inner.secret_key.set(key);
199 }169 }
@@ -243,8 +213,6 @@ impl Store {
243 Ok(user)213 Ok(user)
244 }214 }
245 215
246- /// Inserts an admin only if the users table is empty. One statement, so the check and the
247- /// insert cannot interleave with another creator. Returns `None` if any user already exists.
248 pub async fn create_first_admin(216 pub async fn create_first_admin(
249 &self,217 &self,
250 username: &str,218 username: &str,
@@ -282,7 +250,6 @@ impl Store {
282 .await250 .await
283 }251 }
284 252
285- /// Normalized lookup.
286 pub async fn user_by_username(&self, username: &str) -> Result<Option<User>> {253 pub async fn user_by_username(&self, username: &str) -> Result<Option<User>> {
287 let conn = self.read_conn().await;254 let conn = self.read_conn().await;
288 fetch_opt(255 fetch_opt(
@@ -305,8 +272,6 @@ impl Store {
305 .await272 .await
306 }273 }
307 274
308- /// Changes only the display casing of a username. `display` must validate and fold to the
309- /// user's current `username_folded`; anything else is rejected and nothing is written.
310 pub async fn set_username_display(&self, user_id: &str, display: &str) -> Result<()> {275 pub async fn set_username_display(&self, user_id: &str, display: &str) -> Result<()> {
311 let (display, folded) = validate_username(display)?;276 let (display, folded) = validate_username(display)?;
312 let conn = self.inner.conn.lock().await;277 let conn = self.inner.conn.lock().await;
@@ -366,7 +331,6 @@ impl Store {
366 Ok(session)331 Ok(session)
367 }332 }
368 333
369- /// Only unexpired sessions.
370 pub async fn session_by_token_hash(&self, token_hash: &str) -> Result<Option<Session>> {334 pub async fn session_by_token_hash(&self, token_hash: &str) -> Result<Option<Session>> {
371 let conn = self.read_conn().await;335 let conn = self.read_conn().await;
372 fetch_opt(336 fetch_opt(
@@ -381,7 +345,6 @@ impl Store {
381 .await345 .await
382 }346 }
383 347
384- /// Records a request: bumps `last_seen`, and `last_ip` when the request's address is known.
385 pub async fn touch_session(&self, id: &str, ip: Option<&str>) -> Result<()> {348 pub async fn touch_session(&self, id: &str, ip: Option<&str>) -> Result<()> {
386 let conn = self.inner.conn.lock().await;349 let conn = self.inner.conn.lock().await;
387 conn.execute(350 conn.execute(
@@ -412,7 +375,6 @@ impl Store {
412 Ok(())375 Ok(())
413 }376 }
414 377
415- /// Unexpired sessions for the user, newest first.
416 pub async fn list_sessions(&self, user_id: &str) -> Result<Vec<Session>> {378 pub async fn list_sessions(&self, user_id: &str) -> Result<Vec<Session>> {
417 let conn = self.read_conn().await;379 let conn = self.read_conn().await;
418 fetch_all(380 fetch_all(
@@ -469,7 +431,6 @@ impl Store {
469 Ok(key)431 Ok(key)
470 }432 }
471 433
472- /// Exact byte comparison on the wire-format blob.
473 pub async fn ssh_key_by_blob(&self, key_blob: &[u8]) -> Result<Option<SshKey>> {434 pub async fn ssh_key_by_blob(&self, key_blob: &[u8]) -> Result<Option<SshKey>> {
474 let conn = self.read_conn().await;435 let conn = self.read_conn().await;
475 fetch_opt(436 fetch_opt(
@@ -564,7 +525,6 @@ impl Store {
564 Ok(token)525 Ok(token)
565 }526 }
566 527
567- /// Only unexpired tokens.
568 pub async fn token_by_hash(&self, token_hash: &str) -> Result<Option<AccessToken>> {528 pub async fn token_by_hash(&self, token_hash: &str) -> Result<Option<AccessToken>> {
569 let conn = self.read_conn().await;529 let conn = self.read_conn().await;
570 fetch_opt(530 fetch_opt(
@@ -635,8 +595,6 @@ impl Store {
635 .await595 .await
636 }596 }
637 597
638- /// Inserts a repo row, optionally as a fork of `fork_of`. Shared by `create_repo` and
639- /// `create_fork`.
640 pub(super) async fn insert_repo(598 pub(super) async fn insert_repo(
641 &self,599 &self,
642 owner_id: &str,600 owner_id: &str,
@@ -685,7 +643,6 @@ impl Store {
685 finish(tx, outcome.and_then(|repo| repo.ok_or_else(missing_row))).await643 finish(tx, outcome.and_then(|repo| repo.ok_or_else(missing_row))).await
686 }644 }
687 645
688- /// Normalized. The caller strips a trailing ".git" from `name`.
689 pub async fn repo_by_owner_and_name(&self, owner: &str, name: &str) -> Result<Option<Repo>> {646 pub async fn repo_by_owner_and_name(&self, owner: &str, name: &str) -> Result<Option<Repo>> {
690 let conn = self.read_conn().await;647 let conn = self.read_conn().await;
691 fetch_opt(648 fetch_opt(
@@ -764,7 +721,6 @@ impl Store {
764 Ok((collaborator, org))721 Ok((collaborator, org))
765 }722 }
766 723
767- /// Adds or replaces a collaborator's role on a repo.
768 pub async fn set_collaborator(&self, repo_id: &str, user_id: &str, role: Role) -> Result<()> {724 pub async fn set_collaborator(&self, repo_id: &str, user_id: &str, role: Role) -> Result<()> {
769 let conn = self.inner.conn.lock().await;725 let conn = self.inner.conn.lock().await;
770 conn.execute(726 conn.execute(
@@ -805,8 +761,6 @@ impl Store {
805 Ok(())761 Ok(())
806 }762 }
807 763
808- /// Sets the about text and timezone. `about` is at most 2000 characters and `timezone`
809- /// must be a known IANA name; anything else is rejected and nothing is written.
810 pub async fn set_profile(&self, user_id: &str, about: &str, timezone: &str) -> Result<()> {764 pub async fn set_profile(&self, user_id: &str, about: &str, timezone: &str) -> Result<()> {
811 if about.chars().count() > MAX_ABOUT_CHARS {765 if about.chars().count() > MAX_ABOUT_CHARS {
812 return Err(Error::Invalid(format!(766 return Err(Error::Invalid(format!(
@@ -825,8 +779,6 @@ impl Store {
825 affected(n)779 affected(n)
826 }780 }
827 781
828- /// Sets the display name. `name` goes through `validate_display_name`; an empty name clears
829- /// it (stored as NULL). A rejected name writes nothing.
830 pub async fn set_display_name(&self, user_id: &str, name: &str) -> Result<()> {782 pub async fn set_display_name(&self, user_id: &str, name: &str) -> Result<()> {
831 let name = match validate_display_name(name)? {783 let name = match validate_display_name(name)? {
832 Some(name) => Value::Text(name),784 Some(name) => Value::Text(name),
@@ -876,7 +828,6 @@ impl Store {
876 affected(n)828 affected(n)
877 }829 }
878 830
879- /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest.
880 pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> {831 pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> {
881 let conn = self.inner.conn.lock().await;832 let conn = self.inner.conn.lock().await;
882 conn.execute(833 conn.execute(
@@ -895,7 +846,6 @@ impl Store {
895 Ok(())846 Ok(())
896 }847 }
897 848
898- /// Removes the user's avatar. Succeeds when there is none.
899 pub async fn delete_avatar(&self, user_id: &str) -> Result<()> {849 pub async fn delete_avatar(&self, user_id: &str) -> Result<()> {
900 let conn = self.inner.conn.lock().await;850 let conn = self.inner.conn.lock().await;
901 conn.execute(851 conn.execute(
@@ -918,7 +868,6 @@ impl Store {
918 .await868 .await
919 }869 }
920 870
921- /// The PNG bytes and their hash, if the user has an avatar.
922 pub async fn avatar(&self, user_id: &str) -> Result<Option<(Vec<u8>, String)>> {871 pub async fn avatar(&self, user_id: &str) -> Result<Option<(Vec<u8>, String)>> {
923 let conn = self.read_conn().await;872 let conn = self.read_conn().await;
924 fetch_opt(873 fetch_opt(
@@ -986,7 +935,6 @@ fn missing_row() -> Error {
986 Error::Database("expected a row that is not there".into())935 Error::Database("expected a row that is not there".into())
987 }936 }
988 937
989-/// Maps a failed INSERT: a UNIQUE violation becomes `Conflict`, anything else a database error.
990 fn insert_err(e: turso::Error, conflict_msg: &str) -> Error {938 fn insert_err(e: turso::Error, conflict_msg: &str) -> Error {
991 match e {939 match e {
992 turso::Error::Constraint(ref msg) if msg.to_ascii_uppercase().contains("UNIQUE") => {940 turso::Error::Constraint(ref msg) if msg.to_ascii_uppercase().contains("UNIQUE") => {
@@ -1002,8 +950,6 @@ async fn run_pragma(conn: &Connection, sql: &str) -> std::result::Result<(), tur
1002 Ok(())950 Ok(())
1003 }951 }
1004 952
1005-/// Applies the connection PRAGMAs. Unsupported ones are logged and skipped, never fatal.
1006-/// The values actually in effect are logged after the attempt.
1007 async fn apply_pragmas(conn: &Connection) {953 async fn apply_pragmas(conn: &Connection) {
1008 for sql in [954 for sql in [
1009 "PRAGMA journal_mode = WAL",955 "PRAGMA journal_mode = WAL",
@@ -1046,8 +992,6 @@ where
1046 Ok(out)992 Ok(out)
1047 }993 }
1048 994
1049-/// Refuses with `Invalid(message)` once `count_sql` (one `?1` parameter) counts `max` rows or more.
1050-/// Run under the write lock, before the insert it guards, so two inserts cannot both pass.
1051 async fn refuse_at_limit(995 async fn refuse_at_limit(
1052 conn: &Connection,996 conn: &Connection,
1053 count_sql: &str,997 count_sql: &str,
@@ -1261,13 +1205,6 @@ fn parse_role(s: &str) -> Result<Role> {
1261 }1205 }
1262 1206
1263 impl Store {1207 impl Store {
1264- /// Deletes a repo row and every row that references it (webhooks and their deliveries, issues and their children, labels,
1265- /// milestones, pull requests, notifications, watches and issue subscriptions, redirects, collaborators, push events,
1266- /// branch rules) in one
1267- /// transaction. Pull requests from other repos whose head was this repo keep their row with
1268- /// `head_repo_id` NULL, and forks of this repo keep working with `fork_of` NULL. Returns
1269- /// `NotFound` and changes nothing if the repo is gone.
1270- /// The bare directory on disk is not touched here; the caller moves it to trash.
1271 pub async fn delete_repo(&self, repo_id: &str) -> Result<()> {1208 pub async fn delete_repo(&self, repo_id: &str) -> Result<()> {
1272 let conn = self.inner.conn.lock().await;1209 let conn = self.inner.conn.lock().await;
1273 let tx = conn.unchecked_transaction().await.map_err(db_err)?;1210 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -1324,7 +1261,6 @@ const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_de
1324 require_merge_queue";1261 require_merge_queue";
1325 1262
1326 impl Store {1263 impl Store {
1327- /// The repo's branch rules, ordered by pattern.
1328 pub async fn list_branch_rules(&self, repo_id: &str) -> Result<Vec<BranchRule>> {1264 pub async fn list_branch_rules(&self, repo_id: &str) -> Result<Vec<BranchRule>> {
1329 let conn = self.read_conn().await;1265 let conn = self.read_conn().await;
1330 fetch_all(1266 fetch_all(
@@ -1338,8 +1274,6 @@ impl Store {
1338 .await1274 .await
1339 }1275 }
1340 1276
1341- /// Inserts the rule, or replaces the settings of the rule with the same pattern. `created_at`
1342- /// is kept on update.
1343 pub async fn upsert_branch_rule(1277 pub async fn upsert_branch_rule(
1344 &self,1278 &self,
1345 repo_id: &str,1279 repo_id: &str,
@@ -1391,7 +1325,6 @@ impl Store {
1391 .ok_or_else(missing_row)1325 .ok_or_else(missing_row)
1392 }1326 }
1393 1327
1394- /// Deletes the rule only if it belongs to `repo_id`. Returns `NotFound` otherwise.
1395 pub async fn delete_branch_rule(&self, repo_id: &str, rule_id: &str) -> Result<()> {1328 pub async fn delete_branch_rule(&self, repo_id: &str, rule_id: &str) -> Result<()> {
1396 let conn = self.inner.conn.lock().await;1329 let conn = self.inner.conn.lock().await;
1397 let n = conn1330 let n = conn
@@ -1425,8 +1358,6 @@ fn map_branch_rule(row: &Row) -> Result<BranchRule> {
1425 }1358 }
1426 1359
1427 impl Store {1360 impl Store {
1428- /// The repo a past owner/name points at (both folded). Chains work because a redirect always
1429- /// points at the repo id, not at an intermediate name.
1430 pub async fn repo_by_redirect(&self, owner: &str, name: &str) -> Result<Option<Repo>> {1361 pub async fn repo_by_redirect(&self, owner: &str, name: &str) -> Result<Option<Repo>> {
1431 let conn = self.read_conn().await;1362 let conn = self.read_conn().await;
1432 fetch_opt(1363 fetch_opt(
@@ -1442,25 +1373,15 @@ impl Store {
1442 .await1373 .await
1443 }1374 }
1444 1375
1445- /// Renames a repo under its current owner. The old name keeps working through a redirect.
1446- /// A name taken by another repo of the same owner gives `Conflict`.
1447 pub async fn rename_repo(&self, repo_id: &str, new_name: &str) -> Result<()> {1376 pub async fn rename_repo(&self, repo_id: &str, new_name: &str) -> Result<()> {
1448 validate_name(new_name)?;1377 validate_name(new_name)?;
1449 self.move_repo(repo_id, None, Some(new_name)).await1378 self.move_repo(repo_id, None, Some(new_name)).await
1450 }1379 }
1451 1380
1452- /// Moves a repo to another owner under the same name. The old owner/name keeps working through
1453- /// a redirect. Collaborator rows stay, except the new owner's, which is removed. A name taken
1454- /// by the new owner gives `Conflict`.
1455 pub async fn transfer_repo(&self, repo_id: &str, new_owner_id: &str) -> Result<()> {1381 pub async fn transfer_repo(&self, repo_id: &str, new_owner_id: &str) -> Result<()> {
1456 self.move_repo(repo_id, Some(new_owner_id), None).await1382 self.move_repo(repo_id, Some(new_owner_id), None).await
1457 }1383 }
1458 1384
1459- /// Shared body of rename and transfer, in one transaction. `None` keeps the current owner or
1460- /// name, which is read here under the writer lock so a concurrent move is not written back.
1461- /// Updates owner, name and folded name, records a redirect from the old owner/name to this
1462- /// repo, drops any redirect for the new owner/name, and removes the new owner's collaborator
1463- /// row when the owner changes.
1464 async fn move_repo(1385 async fn move_repo(
1465 &self,1386 &self,
1466 repo_id: &str,1387 repo_id: &str,
@@ -1560,25 +1481,16 @@ impl Store {
1560 }1481 }
1561 }1482 }
1562 1483
1563-/// The two-factor state of a user.
1564 #[derive(Debug, Clone, PartialEq)]1484 #[derive(Debug, Clone, PartialEq)]
1565 pub struct TotpState {1485 pub struct TotpState {
1566- /// The instance-key sealed secret, present once enrollment has started.
1567 pub sealed_secret: Option<String>,1486 pub sealed_secret: Option<String>,
1568- /// True only after the user confirmed a code.
1569 pub enabled: bool,1487 pub enabled: bool,
1570- /// The last time step whose code was accepted (replay guard).
1571 pub last_step: u64,1488 pub last_step: u64,
1572- /// The device name the user gave at enrollment. `None` means the default name.
1573 pub name: Option<String>,1489 pub name: Option<String>,
1574- /// When two-factor was turned on. `None` before that, and for rows from before migration 39.
1575 pub created_at: Option<String>,1490 pub created_at: Option<String>,
1576- /// When a TOTP code last passed. `None` until the first one.
1577 pub last_used_at: Option<String>,1491 pub last_used_at: Option<String>,
1578 }1492 }
1579 1493
1580-/// Checks the basic shape of an email address: one `@`, a non-empty local part and domain,
1581-/// no whitespace or control characters, and at most 254 characters.
1582 pub fn validate_email(email: &str) -> Result<()> {1494 pub fn validate_email(email: &str) -> Result<()> {
1583 let ok = !email.is_empty()1495 let ok = !email.is_empty()
1584 && email.chars().count() <= 2541496 && email.chars().count() <= 254
@@ -1595,7 +1507,6 @@ pub fn validate_email(email: &str) -> Result<()> {
1595 }1507 }
1596 1508
1597 impl Store {1509 impl Store {
1598- /// Sets the user's email address, after [`validate_email`].
1599 pub async fn set_email(&self, user_id: &str, email: &str) -> Result<()> {1510 pub async fn set_email(&self, user_id: &str, email: &str) -> Result<()> {
1600 validate_email(email)?;1511 validate_email(email)?;
1601 let conn = self.inner.conn.lock().await;1512 let conn = self.inner.conn.lock().await;
@@ -1609,7 +1520,6 @@ impl Store {
1609 affected(n)1520 affected(n)
1610 }1521 }
1611 1522
1612- /// Replaces the stored password hash. The caller hashes the password.
1613 pub async fn set_password_hash(&self, user_id: &str, password_hash: &str) -> Result<()> {1523 pub async fn set_password_hash(&self, user_id: &str, password_hash: &str) -> Result<()> {
1614 let conn = self.inner.conn.lock().await;1524 let conn = self.inner.conn.lock().await;
1615 let n = conn1525 let n = conn
@@ -1646,7 +1556,6 @@ impl Store {
1646 finish(tx, outcome).await1556 finish(tx, outcome).await
1647 }1557 }
1648 1558
1649- /// Deletes every session of the user except `keep_session_id`. Returns how many were removed.
1650 pub async fn delete_sessions_except(1559 pub async fn delete_sessions_except(
1651 &self,1560 &self,
1652 user_id: &str,1561 user_id: &str,
@@ -1661,7 +1570,6 @@ impl Store {
1661 .map_err(db_err)1570 .map_err(db_err)
1662 }1571 }
1663 1572
1664- /// The two-factor state, or `None` when the user does not exist.
1665 pub async fn totp_state(&self, user_id: &str) -> Result<Option<TotpState>> {1573 pub async fn totp_state(&self, user_id: &str) -> Result<Option<TotpState>> {
1666 let conn = self.read_conn().await;1574 let conn = self.read_conn().await;
1667 fetch_opt(1575 fetch_opt(
@@ -1691,8 +1599,6 @@ impl Store {
1691 .await1599 .await
1692 }1600 }
1693 1601
1694- /// Stores a sealed secret for an enrollment that is not yet confirmed (`enabled` stays 0).
1695- /// Replay state is reset, because the secret is new.
1696 pub async fn set_totp_secret(&self, user_id: &str, sealed: &str) -> Result<()> {1602 pub async fn set_totp_secret(&self, user_id: &str, sealed: &str) -> Result<()> {
1697 let conn = self.inner.conn.lock().await;1603 let conn = self.inner.conn.lock().await;
1698 let n = conn1604 let n = conn
@@ -1707,9 +1613,6 @@ impl Store {
1707 affected(n)1613 affected(n)
1708 }1614 }
1709 1615
1710- /// Turns two-factor on after a confirmed code, and replaces the recovery codes with
1711- /// `code_hashes`. The step of the confirming code is recorded so it cannot be replayed.
1712- /// Runs in one transaction.
1713 pub async fn enable_totp(1616 pub async fn enable_totp(
1714 &self,1617 &self,
1715 user_id: &str,1618 user_id: &str,
@@ -1738,7 +1641,6 @@ impl Store {
1738 finish(tx, outcome).await1641 finish(tx, outcome).await
1739 }1642 }
1740 1643
1741- /// Replaces the user's recovery codes with `code_hashes`. Used by regeneration.
1742 pub async fn replace_recovery_codes(1644 pub async fn replace_recovery_codes(
1743 &self,1645 &self,
1744 user_id: &str,1646 user_id: &str,
@@ -1750,7 +1652,6 @@ impl Store {
1750 finish(tx, outcome).await1652 finish(tx, outcome).await
1751 }1653 }
1752 1654
1753- /// Turns two-factor off: clears the secret, the replay state and all recovery codes.
1754 pub async fn disable_totp(&self, user_id: &str) -> Result<()> {1655 pub async fn disable_totp(&self, user_id: &str) -> Result<()> {
1755 let conn = self.inner.conn.lock().await;1656 let conn = self.inner.conn.lock().await;
1756 let tx = conn.unchecked_transaction().await.map_err(db_err)?;1657 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -1776,8 +1677,6 @@ impl Store {
1776 finish(tx, outcome).await1677 finish(tx, outcome).await
1777 }1678 }
1778 1679
1779- /// Advances the replay guard to `step`. Returns false, and changes nothing, when `step` is
1780- /// not later than the last accepted step. The check and the update are one statement.
1781 pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result<bool> {1680 pub async fn accept_totp_step(&self, user_id: &str, step: u64) -> Result<bool> {
1782 let step = i64::try_from(step).map_err(|_| Error::Invalid("step".into()))?;1681 let step = i64::try_from(step).map_err(|_| Error::Invalid("step".into()))?;
1783 let conn = self.inner.conn.lock().await;1682 let conn = self.inner.conn.lock().await;
@@ -1792,7 +1691,6 @@ impl Store {
1792 Ok(n > 0)1691 Ok(n > 0)
1793 }1692 }
1794 1693
1795- /// Sets the device name shown on the security page. `None` restores the default name.
1796 pub async fn set_totp_name(&self, user_id: &str, name: Option<&str>) -> Result<()> {1694 pub async fn set_totp_name(&self, user_id: &str, name: Option<&str>) -> Result<()> {
1797 let conn = self.inner.conn.lock().await;1695 let conn = self.inner.conn.lock().await;
1798 let value = match name {1696 let value = match name {
@@ -1808,7 +1706,6 @@ impl Store {
1808 Ok(())1706 Ok(())
1809 }1707 }
1810 1708
1811- /// When the password last changed, or `None` when no change was recorded since migration 39.
1812 pub async fn password_changed_at(&self, user_id: &str) -> Result<Option<String>> {1709 pub async fn password_changed_at(&self, user_id: &str) -> Result<Option<String>> {
1813 let conn = self.read_conn().await;1710 let conn = self.read_conn().await;
1814 fetch_opt(1711 fetch_opt(
@@ -1821,7 +1718,6 @@ impl Store {
1821 .map(Option::flatten)1718 .map(Option::flatten)
1822 }1719 }
1823 1720
1824- /// Marks an unused recovery code as used. Returns false when no unused code has this hash.
1825 pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result<bool> {1721 pub async fn consume_recovery_code(&self, user_id: &str, code_hash: &str) -> Result<bool> {
1826 let conn = self.inner.conn.lock().await;1722 let conn = self.inner.conn.lock().await;
1827 let n = conn1723 let n = conn
@@ -1835,7 +1731,6 @@ impl Store {
1835 Ok(n > 0)1731 Ok(n > 0)
1836 }1732 }
1837 1733
1838- /// How many recovery codes the user has not used yet.
1839 pub async fn unused_recovery_codes(&self, user_id: &str) -> Result<u64> {1734 pub async fn unused_recovery_codes(&self, user_id: &str) -> Result<u64> {
1840 let conn = self.read_conn().await;1735 let conn = self.read_conn().await;
1841 fetch_opt(1736 fetch_opt(
@@ -1849,7 +1744,6 @@ impl Store {
1849 }1744 }
1850 }1745 }
1851 1746
1852-/// Replaces a user's recovery codes inside an open transaction.
1853 async fn replace_codes_in(1747 async fn replace_codes_in(
1854 tx: &turso::transaction::Transaction<'_>,1748 tx: &turso::transaction::Transaction<'_>,
1855 user_id: &str,1749 user_id: &str,
@@ -1872,7 +1766,6 @@ async fn replace_codes_in(
1872 Ok(())1766 Ok(())
1873 }1767 }
1874 1768
1875-/// Commits when `outcome` is Ok and rolls back otherwise, returning the outcome.
1876 async fn finish<T>(tx: turso::transaction::Transaction<'_>, outcome: Result<T>) -> Result<T> {1769 async fn finish<T>(tx: turso::transaction::Transaction<'_>, outcome: Result<T>) -> Result<T> {
1877 match outcome {1770 match outcome {
1878 Ok(value) => {1771 Ok(value) => {
@@ -2302,7 +2195,6 @@ mod tests {
2302 }2195 }
2303 2196
2304 impl Store {2197 impl Store {
2305- /// Every collaborator on a repo with their role, ordered by username (case-insensitive).
2306 pub async fn list_collaborators(&self, repo_id: &str) -> Result<Vec<(User, Role)>> {2198 pub async fn list_collaborators(&self, repo_id: &str) -> Result<Vec<(User, Role)>> {
2307 let conn = self.read_conn().await;2199 let conn = self.read_conn().await;
2308 fetch_all(2200 fetch_all(
@@ -2318,7 +2210,6 @@ impl Store {
2318 .await2210 .await
2319 }2211 }
2320 2212
2321- /// Removes a collaborator from a repo. Returns false when the user was not a collaborator.
2322 pub async fn remove_collaborator(&self, repo_id: &str, user_id: &str) -> Result<bool> {2213 pub async fn remove_collaborator(&self, repo_id: &str, user_id: &str) -> Result<bool> {
2323 let conn = self.inner.conn.lock().await;2214 let conn = self.inner.conn.lock().await;
2324 let n = conn2215 let n = conn
@@ -2332,13 +2223,9 @@ impl Store {
2332 }2223 }
2333 }2224 }
2334 2225
2335-/// Longest accepted repo description, in characters.
2336 pub const MAX_DESCRIPTION_CHARS: usize = 350;2226 pub const MAX_DESCRIPTION_CHARS: usize = 350;
2337 2227
2338 impl Store {2228 impl Store {
2339- /// Saves the description and the default branch in one statement. The description must be at
2340- /// most `MAX_DESCRIPTION_CHARS` characters with no control characters. The branch is not checked
2341- /// here: the caller confirms it exists and points git HEAD at it first.
2342 pub async fn update_repo_general(2229 pub async fn update_repo_general(
2343 &self,2230 &self,
2344 repo_id: &str,2231 repo_id: &str,
@@ -2373,7 +2260,6 @@ impl Store {
2373 affected(n)2260 affected(n)
2374 }2261 }
2375 2262
2376- /// Sets the repo's visibility. `NotFound` when the repo is gone.
2377 pub async fn set_repo_visibility(&self, repo_id: &str, v: Visibility) -> Result<()> {2263 pub async fn set_repo_visibility(&self, repo_id: &str, v: Visibility) -> Result<()> {
2378 let conn = self.inner.conn.lock().await;2264 let conn = self.inner.conn.lock().await;
2379 let n = conn2265 let n = conn
@@ -2448,22 +2334,16 @@ mod collaborator_tests {
2448 }2334 }
2449 }2335 }
2450 2336
2451-/// Sort order for the public repo listing.
2452 #[derive(Debug, Clone, Copy, PartialEq, Eq)]2337 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2453 pub enum RepoSort {2338 pub enum RepoSort {
2454- /// Latest push, or the creation time when the repo was never pushed to.
2455 RecentlyUpdated,2339 RecentlyUpdated,
2456- /// Most stars first.
2457 MostStars,2340 MostStars,
2458- /// Alphabetical by name, case-insensitive.
2459 Name,2341 Name,
2460 }2342 }
2461 2343
2462-/// A row of the public listing: the repo, its star count and its last activity time.
2463 pub type ListedRepo = (Repo, u64, String);2344 pub type ListedRepo = (Repo, u64, String);
2464 2345
2465 impl Store {2346 impl Store {
2466- /// Stars a repo for a user. Starring a repo twice changes nothing.
2467 pub async fn star(&self, user_id: &str, repo_id: &str) -> Result<()> {2347 pub async fn star(&self, user_id: &str, repo_id: &str) -> Result<()> {
2468 let conn = self.inner.conn.lock().await;2348 let conn = self.inner.conn.lock().await;
2469 conn.execute(2349 conn.execute(
@@ -2475,7 +2355,6 @@ impl Store {
2475 Ok(())2355 Ok(())
2476 }2356 }
2477 2357
2478- /// Removes a user's star on a repo. Removing a missing star changes nothing.
2479 pub async fn unstar(&self, user_id: &str, repo_id: &str) -> Result<()> {2358 pub async fn unstar(&self, user_id: &str, repo_id: &str) -> Result<()> {
2480 let conn = self.inner.conn.lock().await;2359 let conn = self.inner.conn.lock().await;
2481 conn.execute(2360 conn.execute(
@@ -2487,7 +2366,6 @@ impl Store {
2487 Ok(())2366 Ok(())
2488 }2367 }
2489 2368
2490- /// Whether the user has starred the repo.
2491 pub async fn is_starred(&self, user_id: &str, repo_id: &str) -> Result<bool> {2369 pub async fn is_starred(&self, user_id: &str, repo_id: &str) -> Result<bool> {
2492 let conn = self.read_conn().await;2370 let conn = self.read_conn().await;
2493 Ok(fetch_opt(2371 Ok(fetch_opt(
@@ -2500,7 +2378,6 @@ impl Store {
2500 .is_some())2378 .is_some())
2501 }2379 }
2502 2380
2503- /// How many users have starred the repo.
2504 pub async fn star_count(&self, repo_id: &str) -> Result<u64> {2381 pub async fn star_count(&self, repo_id: &str) -> Result<u64> {
2505 let conn = self.read_conn().await;2382 let conn = self.read_conn().await;
2506 let n = fetch_opt(2383 let n = fetch_opt(
@@ -2514,11 +2391,6 @@ impl Store {
2514 Ok(u64::try_from(n).unwrap_or(0))2391 Ok(u64::try_from(n).unwrap_or(0))
2515 }2392 }
2516 2393
2517- /// One page of public repos, optionally filtered by `query`. The query matches the repo name
2518- /// or description, case-insensitively, as a plain substring: `%`, `_` and `\` are literal.
2519- /// Each row carries the star count and the last activity time (the latest push, or the
2520- /// creation time). Returns the rows for `page` (1-based, clamped to the last page) and the
2521- /// total number of matches.
2522 pub async fn list_public_repos(2394 pub async fn list_public_repos(
2523 &self,2395 &self,
2524 query: Option<&str>,2396 query: Option<&str>,
crates/forge-core/src/store/needs.rsmodified+0 -52
@@ -1,8 +1,3 @@
1-//! What is waiting on the signed-in user, for the `/needs-you` page: their failing CI runs, their
2-//! own open pull requests that carry a review verdict, their assigned open issues and their unread
3-//! mentions. Reads only. Every query applies the viewer's readable-repo rule (`readable_repo`), as
4-//! the other per-user lists do. Review requests come from `review_requests_for_user`.
5-
6 use std::time::Duration;1 use std::time::Duration;
7 2
8 use turso::Value;3 use turso::Value;
@@ -14,64 +9,42 @@ use crate::error::Result;
14 use crate::notifications::Reason;9 use crate::notifications::Reason;
15 use crate::time::{now_stamp, stamp_ago};10 use crate::time::{now_stamp, stamp_ago};
16 11
17-/// How far back a failing run counts, here and in the profile corner's failing count.
18 pub(super) const FAILING_WINDOW: Duration = Duration::from_secs(7 * 24 * 60 * 60);12 pub(super) const FAILING_WINDOW: Duration = Duration::from_secs(7 * 24 * 60 * 60);
19 13
20-/// A ref whose newest run by the user failed within `FAILING_WINDOW`.
21 #[derive(Debug, Clone)]14 #[derive(Debug, Clone)]
22 pub struct FailingRun {15 pub struct FailingRun {
23- /// Owner username of the repo.
24 pub owner: String,16 pub owner: String,
25- /// Repo name.
26 pub repo: String,17 pub repo: String,
27- /// Run number within the repo.
28 pub number: i64,18 pub number: i64,
29- /// Git ref the run ran on.
30 pub git_ref: String,19 pub git_ref: String,
31- /// When the run was created.
32 pub created_at: String,20 pub created_at: String,
33 }21 }
34 22
35-/// The review verdict on a pull request. Changes requested wins over approval.
36 #[derive(Debug, Clone, Copy, PartialEq, Eq)]23 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
37 pub enum Verdict {24 pub enum Verdict {
38 ChangesRequested,25 ChangesRequested,
39 Approved,26 Approved,
40 }27 }
41 28
42-/// An open pull request the user authored, with a review verdict.
43 #[derive(Debug, Clone)]29 #[derive(Debug, Clone)]
44 pub struct OwnPull {30 pub struct OwnPull {
45- /// Owner username of the repo.
46 pub owner: String,31 pub owner: String,
47- /// Repo name.
48 pub repo: String,32 pub repo: String,
49- /// Pull request number.
50 pub number: i64,33 pub number: i64,
51- /// Title of the pull request.
52 pub title: String,34 pub title: String,
53- /// The verdict from the latest review of each reviewer.
54 pub verdict: Verdict,35 pub verdict: Verdict,
55- /// When the pull request last changed.
56 pub updated_at: String,36 pub updated_at: String,
57 }37 }
58 38
59-/// An open issue assigned to the user.
60 #[derive(Debug, Clone)]39 #[derive(Debug, Clone)]
61 pub struct AssignedIssue {40 pub struct AssignedIssue {
62- /// Owner username of the repo.
63 pub owner: String,41 pub owner: String,
64- /// Repo name.
65 pub repo: String,42 pub repo: String,
66- /// Issue number.
67 pub number: i64,43 pub number: i64,
68- /// Title of the issue.
69 pub title: String,44 pub title: String,
70- /// When the issue last changed.
71 pub updated_at: String,45 pub updated_at: String,
72 }46 }
73 47
74-/// The failing runs query without its page, newest first.
75 pub(super) fn failing_runs_sql(readable: &str) -> String {48 pub(super) fn failing_runs_sql(readable: &str) -> String {
76 format!(49 format!(
77 "SELECT owner, name, number, git_ref, created_at FROM ( \50 "SELECT owner, name, number, git_ref, created_at FROM ( \
@@ -87,8 +60,6 @@ pub(super) fn failing_runs_sql(readable: &str) -> String {
87 )60 )
88 }61 }
89 62
90-/// The open pull requests with a verdict, without their page, newest first. Each row's last
91-/// column is 1 when the latest review of some reviewer asks for changes, 0 when all approve.
92 fn own_pulls_sql(readable: &str) -> String {63 fn own_pulls_sql(readable: &str) -> String {
93 format!(64 format!(
94 "SELECT o.username, r.name, i.number, i.title, i.updated_at, v.changes_requested \65 "SELECT o.username, r.name, i.number, i.title, i.updated_at, v.changes_requested \
@@ -106,7 +77,6 @@ fn own_pulls_sql(readable: &str) -> String {
106 )77 )
107 }78 }
108 79
109-/// The assigned open issues without their page, newest first.
110 fn assigned_issues_sql(readable: &str) -> String {80 fn assigned_issues_sql(readable: &str) -> String {
111 format!(81 format!(
112 "SELECT o.username, r.name, i.number, i.title, i.updated_at FROM issue_assignees ia \82 "SELECT o.username, r.name, i.number, i.title, i.updated_at FROM issue_assignees ia \
@@ -118,8 +88,6 @@ fn assigned_issues_sql(readable: &str) -> String {
118 )88 )
119 }89 }
120 90
121-/// The unread mentions without their page, newest first. The same rule as `waiting_on`, with the
122-/// reason fixed to a mention.
123 fn mentions_sql(readable: &str) -> String {91 fn mentions_sql(readable: &str) -> String {
124 format!(92 format!(
125 "SELECT o.username, r.name, i.number, i.kind, i.title, n.updated_at \93 "SELECT o.username, r.name, i.number, i.kind, i.title, n.updated_at \
@@ -133,14 +101,12 @@ fn mentions_sql(readable: &str) -> String {
133 )101 )
134 }102 }
135 103
136-/// Binds the viewer id, then the readable-repo parameters, as every query here does.
137 fn viewer_params(user_id: &str) -> Vec<Value> {104 fn viewer_params(user_id: &str) -> Vec<Value> {
138 let mut params = vec![Value::Text(user_id.to_string())];105 let mut params = vec![Value::Text(user_id.to_string())];
139 params.extend(readable_params(user_id));106 params.extend(readable_params(user_id));
140 params107 params
141 }108 }
142 109
143-/// The parameters of `failing_runs_sql`, in order.
144 pub(super) fn failing_runs_params(user_id: &str) -> Vec<Value> {110 pub(super) fn failing_runs_params(user_id: &str) -> Vec<Value> {
145 let mut params = viewer_params(user_id);111 let mut params = viewer_params(user_id);
146 params.push(Value::Text(stamp_ago(FAILING_WINDOW)));112 params.push(Value::Text(stamp_ago(FAILING_WINDOW)));
@@ -148,13 +114,11 @@ pub(super) fn failing_runs_params(user_id: &str) -> Vec<Value> {
148 params114 params
149 }115 }
150 116
151-/// `base` with its page: `LIMIT` and `OFFSET` are the last two placeholders.
152 fn paged(base: &str) -> String {117 fn paged(base: &str) -> String {
153 format!("{base} LIMIT ? OFFSET ?")118 format!("{base} LIMIT ? OFFSET ?")
154 }119 }
155 120
156 impl Store {121 impl Store {
157- /// The number of rows a query without its page returns.
158 async fn count_rows(&self, base: &str, params: Vec<Value>) -> Result<u64> {122 async fn count_rows(&self, base: &str, params: Vec<Value>) -> Result<u64> {
159 let conn = self.read_conn().await;123 let conn = self.read_conn().await;
160 let counts = fetch_all(124 let counts = fetch_all(
@@ -170,8 +134,6 @@ impl Store {
170 .unwrap_or(0))134 .unwrap_or(0))
171 }135 }
172 136
173- /// The user's newest run per (repo, ref) when it failed within the failing window, newest
174- /// first, one page at a time. Runs in repos the user cannot read are left out.
175 pub async fn failing_runs(137 pub async fn failing_runs(
176 &self,138 &self,
177 actor_id: &str,139 actor_id: &str,
@@ -199,7 +161,6 @@ impl Store {
199 .await161 .await
200 }162 }
201 163
202- /// Hides the user's failed runs that have finished so far. A run that fails later shows again.
203 pub async fn dismiss_failed_runs(&self, user_id: &str) -> Result<()> {164 pub async fn dismiss_failed_runs(&self, user_id: &str) -> Result<()> {
204 let conn = self.inner.conn.lock().await;165 let conn = self.inner.conn.lock().await;
205 conn.execute(166 conn.execute(
@@ -211,17 +172,12 @@ impl Store {
211 Ok(())172 Ok(())
212 }173 }
213 174
214- /// How many failing runs `failing_runs` lists in all.
215 pub async fn failing_runs_total(&self, actor_id: &str) -> Result<u64> {175 pub async fn failing_runs_total(&self, actor_id: &str) -> Result<u64> {
216 let params = failing_runs_params(actor_id);176 let params = failing_runs_params(actor_id);
217 self.count_rows(&failing_runs_sql(&readable_repo()), params)177 self.count_rows(&failing_runs_sql(&readable_repo()), params)
218 .await178 .await
219 }179 }
220 180
221- /// Open pull requests the user authored that have a changes-requested or an approving review,
222- /// newest first, one page at a time. A pull with a change request is listed as changes
223- /// requested even when someone else approved it. Pulls in repos the user cannot read are left
224- /// out.
225 pub async fn own_pulls_with_verdict(181 pub async fn own_pulls_with_verdict(
226 &self,182 &self,
227 author_id: &str,183 author_id: &str,
@@ -254,14 +210,11 @@ impl Store {
254 .await210 .await
255 }211 }
256 212
257- /// How many pull requests `own_pulls_with_verdict` lists in all.
258 pub async fn own_pulls_total(&self, author_id: &str) -> Result<u64> {213 pub async fn own_pulls_total(&self, author_id: &str) -> Result<u64> {
259 self.count_rows(&own_pulls_sql(&readable_repo()), viewer_params(author_id))214 self.count_rows(&own_pulls_sql(&readable_repo()), viewer_params(author_id))
260 .await215 .await
261 }216 }
262 217
263- /// Open issues assigned to the user, newest first, one page at a time. Pull requests are not
264- /// listed. Issues in repos the user cannot read are left out.
265 pub async fn assigned_issues(218 pub async fn assigned_issues(
266 &self,219 &self,
267 user_id: &str,220 user_id: &str,
@@ -289,7 +242,6 @@ impl Store {
289 .await242 .await
290 }243 }
291 244
292- /// How many issues `assigned_issues` lists in all.
293 pub async fn assigned_issues_total(&self, user_id: &str) -> Result<u64> {245 pub async fn assigned_issues_total(&self, user_id: &str) -> Result<u64> {
294 self.count_rows(246 self.count_rows(
295 &assigned_issues_sql(&readable_repo()),247 &assigned_issues_sql(&readable_repo()),
@@ -298,8 +250,6 @@ impl Store {
298 .await250 .await
299 }251 }
300 252
301- /// The user's unread mentions, newest first, one page at a time. Mentions in repos the user
302- /// cannot read are left out.
303 pub async fn mentions_waiting(253 pub async fn mentions_waiting(
304 &self,254 &self,
305 user_id: &str,255 user_id: &str,
@@ -329,7 +279,6 @@ impl Store {
329 .await279 .await
330 }280 }
331 281
332- /// How many mentions `mentions_waiting` lists in all.
333 pub async fn mentions_total(&self, user_id: &str) -> Result<u64> {282 pub async fn mentions_total(&self, user_id: &str) -> Result<u64> {
334 self.count_rows(&mentions_sql(&readable_repo()), viewer_params(user_id))283 self.count_rows(&mentions_sql(&readable_repo()), viewer_params(user_id))
335 .await284 .await
@@ -364,7 +313,6 @@ mod tests {
364 .unwrap();313 .unwrap();
365 assert_eq!(store.assigned_issues(&bob.id, 8, 0).await.unwrap().len(), 1);314 assert_eq!(store.assigned_issues(&bob.id, 8, 0).await.unwrap().len(), 1);
366 315
367- // Once the repo is private and bob is not a collaborator, the assignment stays but is hidden.
368 store316 store
369 .set_repo_visibility(&repo.id, Visibility::Private)317 .set_repo_visibility(&repo.id, Visibility::Private)
370 .await318 .await
crates/forge-core/src/store/notifications.rsmodified+0 -41
@@ -1,5 +1,3 @@
1-//! Notification storage: repo watch levels, issue subscriptions and inbox rows.
2-
3 use turso::transaction::Transaction;1 use turso::transaction::Transaction;
4 use turso::{Row, Value};2 use turso::{Row, Value};
5 3
@@ -12,25 +10,18 @@ use crate::model::{Id, User};
12 use crate::notifications::{Notification, Reason, SubState, WatchLevel};10 use crate::notifications::{Notification, Reason, SubState, WatchLevel};
13 use crate::time::now_stamp;11 use crate::time::now_stamp;
14 12
15-/// Largest page `list_notifications` returns, whatever the caller asks for.
16 const MAX_NOTIFICATION_PAGE: u32 = 200;13 const MAX_NOTIFICATION_PAGE: u32 = 200;
17 14
18-/// The condition under which the inbox owner may still read repo `r`: the read rule, or an
19-/// instance admin. Takes the user id five times. A repo made private, or one the user was removed
20-/// from, drops out of the inbox, the dashboard and the unread count at once.
21 pub(super) fn readable_repo() -> String {15 pub(super) fn readable_repo() -> String {
22 format!(16 format!(
23 "((r.visibility = 'public' OR {VIEWER_ACCESS}) OR EXISTS (SELECT 1 FROM users ua WHERE ua.id = ? AND ua.is_admin = 1))"17 "((r.visibility = 'public' OR {VIEWER_ACCESS}) OR EXISTS (SELECT 1 FROM users ua WHERE ua.id = ? AND ua.is_admin = 1))"
24 )18 )
25 }19 }
26 20
27-/// The user id, bound once per `?` of `readable_repo`.
28 pub(super) fn readable_params(user_id: &str) -> impl Iterator<Item = Value> + '_ {21 pub(super) fn readable_params(user_id: &str) -> impl Iterator<Item = Value> + '_ {
29 (0..5).map(move |_| Value::Text(user_id.to_string()))22 (0..5).map(move |_| Value::Text(user_id.to_string()))
30 }23 }
31 24
32-/// Inbox rows joined with their repo, owner, issue or pull, and last actor. `?` placeholders
33-/// are appended to by `list_notifications`.
34 const NOTIFICATION_SELECT: &str = "SELECT n.id, n.repo_id, o.username, r.name, n.issue_id, \25 const NOTIFICATION_SELECT: &str = "SELECT n.id, n.repo_id, o.username, r.name, n.issue_id, \
35 i.number, i.kind, i.title, i.state, n.reason, n.last_activity, a.username, n.unread, \26 i.number, i.kind, i.title, i.state, n.reason, n.last_activity, a.username, n.unread, \
36 n.updated_at FROM notifications n \27 n.updated_at FROM notifications n \
@@ -74,8 +65,6 @@ fn map_notification(row: &Row) -> Result<Notification> {
74 })65 })
75 }66 }
76 67
77-/// Deletes the notification rows of one repo: its inbox rows, the subscriptions on its issues
78-/// and its watches. Must run before the issues themselves are deleted.
79 pub(super) async fn delete_repo_notification_rows(68 pub(super) async fn delete_repo_notification_rows(
80 tx: &Transaction<'_>,69 tx: &Transaction<'_>,
81 repo_id: &str,70 repo_id: &str,
@@ -100,7 +89,6 @@ impl Store {
100 .await89 .await
101 }90 }
102 91
103- /// Sets the user's watch level on a repo, creating the row if needed.
104 pub async fn set_watch(&self, user_id: &str, repo_id: &str, level: WatchLevel) -> Result<()> {92 pub async fn set_watch(&self, user_id: &str, repo_id: &str, level: WatchLevel) -> Result<()> {
105 let conn = self.inner.conn.lock().await;93 let conn = self.inner.conn.lock().await;
106 conn.execute(94 conn.execute(
@@ -118,7 +106,6 @@ impl Store {
118 Ok(())106 Ok(())
119 }107 }
120 108
121- /// The user's watch level on a repo. No row means `Participating`.
122 pub async fn watch_level(&self, user_id: &str, repo_id: &str) -> Result<WatchLevel> {109 pub async fn watch_level(&self, user_id: &str, repo_id: &str) -> Result<WatchLevel> {
123 let conn = self.read_conn().await;110 let conn = self.read_conn().await;
124 let level = fetch_opt(111 let level = fetch_opt(
@@ -134,7 +121,6 @@ impl Store {
134 }121 }
135 }122 }
136 123
137- /// Users watching the repo at level `watching`, ordered by id.
138 pub async fn watchers(&self, repo_id: &str) -> Result<Vec<Id>> {124 pub async fn watchers(&self, repo_id: &str) -> Result<Vec<Id>> {
139 let conn = self.read_conn().await;125 let conn = self.read_conn().await;
140 fetch_all(126 fetch_all(
@@ -146,7 +132,6 @@ impl Store {
146 .await132 .await
147 }133 }
148 134
149- /// How many users watch the repo at level `watching` (the count of `watchers`).
150 pub async fn watcher_count(&self, repo_id: &str) -> Result<u64> {135 pub async fn watcher_count(&self, repo_id: &str) -> Result<u64> {
151 let conn = self.read_conn().await;136 let conn = self.read_conn().await;
152 let n = fetch_opt(137 let n = fetch_opt(
@@ -160,7 +145,6 @@ impl Store {
160 Ok(u64::try_from(n).unwrap_or(0))145 Ok(u64::try_from(n).unwrap_or(0))
161 }146 }
162 147
163- /// The site admins (accounts with `is_admin` set), ordered by username.
164 pub async fn list_admins(&self) -> Result<Vec<User>> {148 pub async fn list_admins(&self) -> Result<Vec<User>> {
165 let conn = self.read_conn().await;149 let conn = self.read_conn().await;
166 fetch_all(150 fetch_all(
@@ -172,8 +156,6 @@ impl Store {
172 .await156 .await
173 }157 }
174 158
175- /// Sets the user's subscription on an issue or pull, replacing any existing row. This is
176- /// the explicit user action.
177 pub async fn subscribe(159 pub async fn subscribe(
178 &self,160 &self,
179 user_id: &str,161 user_id: &str,
@@ -199,8 +181,6 @@ impl Store {
199 Ok(())181 Ok(())
200 }182 }
201 183
202- /// Subscribes the user as `subscribed` with `reason`, but only when no row exists yet. An
203- /// existing row, including an explicit `ignored` one, is left alone.
204 pub async fn auto_subscribe(184 pub async fn auto_subscribe(
205 &self,185 &self,
206 user_id: &str,186 user_id: &str,
@@ -224,7 +204,6 @@ impl Store {
224 Ok(())204 Ok(())
225 }205 }
226 206
227- /// The user's subscription row on an issue, if any.
228 pub async fn subscription(207 pub async fn subscription(
229 &self,208 &self,
230 user_id: &str,209 user_id: &str,
@@ -245,8 +224,6 @@ impl Store {
245 Ok(row)224 Ok(row)
246 }225 }
247 226
248- /// Users subscribed to an issue (state `subscribed`, not `ignored`), with their stored
249- /// reason, ordered by user id.
250 pub async fn subscribers(&self, issue_id: &str) -> Result<Vec<(Id, Reason)>> {227 pub async fn subscribers(&self, issue_id: &str) -> Result<Vec<(Id, Reason)>> {
251 let conn = self.read_conn().await;228 let conn = self.read_conn().await;
252 fetch_all(229 fetch_all(
@@ -259,11 +236,6 @@ impl Store {
259 .await236 .await
260 }237 }
261 238
262- /// Records activity on a thread for one user and marks it unread.
263- ///
264- /// The reason is the stronger of `reason` and the stored one while the row is unread. Once
265- /// the row has been read, `reason` replaces the stored one. `activity` is the activity
266- /// name (`comment`, `opened`, ...) and `actor_id` the user who acted, if any.
267 pub async fn upsert_notification(239 pub async fn upsert_notification(
268 &self,240 &self,
269 user_id: &str,241 user_id: &str,
@@ -339,11 +311,6 @@ impl Store {
339 finish(tx, outcome).await311 finish(tx, outcome).await
340 }312 }
341 313
342- /// The user's inbox, newest activity first (`updated_at`, then id).
343- ///
344- /// `unread_only` keeps only unread rows. `before` is the `updated_at` of the last row of the
345- /// previous page; it returns rows strictly older than that stamp. `limit` is clamped to
346- /// 1..=200.
347 pub async fn list_notifications(314 pub async fn list_notifications(
348 &self,315 &self,
349 user_id: &str,316 user_id: &str,
@@ -372,8 +339,6 @@ impl Store {
372 fetch_all(&conn, &sql, params, map_notification).await339 fetch_all(&conn, &sql, params, map_notification).await
373 }340 }
374 341
375- /// Number of unread inbox rows of the user, issues and discussions together. Rows of repos the
376- /// user can no longer read are left out.
377 pub async fn unread_count(&self, user_id: &str) -> Result<u64> {342 pub async fn unread_count(&self, user_id: &str) -> Result<u64> {
378 let readable = readable_repo();343 let readable = readable_repo();
379 let sql = format!(344 let sql = format!(
@@ -398,7 +363,6 @@ impl Store {
398 u64::try_from(n).map_err(|_| Error::Database("negative count".into()))363 u64::try_from(n).map_err(|_| Error::Database("negative count".into()))
399 }364 }
400 365
401- /// Marks one inbox row read. Another user's row id changes nothing.
402 pub async fn mark_read(&self, user_id: &str, notification_id: &str) -> Result<()> {366 pub async fn mark_read(&self, user_id: &str, notification_id: &str) -> Result<()> {
403 let conn = self.inner.conn.lock().await;367 let conn = self.inner.conn.lock().await;
404 conn.execute(368 conn.execute(
@@ -410,8 +374,6 @@ impl Store {
410 Ok(())374 Ok(())
411 }375 }
412 376
413- /// Marks the user's unread rows read, in one repo when `repo_id` is given, otherwise all of
414- /// them.
415 pub async fn mark_all_read(&self, user_id: &str, repo_id: Option<&str>) -> Result<()> {377 pub async fn mark_all_read(&self, user_id: &str, repo_id: Option<&str>) -> Result<()> {
416 let conn = self.inner.conn.lock().await;378 let conn = self.inner.conn.lock().await;
417 conn.execute(379 conn.execute(
@@ -423,7 +385,6 @@ impl Store {
423 Ok(())385 Ok(())
424 }386 }
425 387
426- /// Marks the user's row for one issue or pull read. Called when the user views it.
427 pub async fn mark_issue_read(&self, user_id: &str, issue_id: &str) -> Result<()> {388 pub async fn mark_issue_read(&self, user_id: &str, issue_id: &str) -> Result<()> {
428 let conn = self.inner.conn.lock().await;389 let conn = self.inner.conn.lock().await;
429 conn.execute(390 conn.execute(
@@ -486,7 +447,6 @@ mod tests {
486 }447 }
487 }448 }
488 449
489- /// One integer from a query with a single text parameter.
490 async fn count(store: &Store, sql: &str, param: &str) -> i64 {450 async fn count(store: &Store, sql: &str, param: &str) -> i64 {
491 let conn = store.inner.conn.lock().await;451 let conn = store.inner.conn.lock().await;
492 fetch_opt(&conn, sql, (param.to_string(),), |row| col_int(row, 0))452 fetch_opt(&conn, sql, (param.to_string(),), |row| col_int(row, 0))
@@ -507,7 +467,6 @@ mod tests {
507 .reason467 .reason
508 }468 }
509 469
510- /// A user with a unique name, so per-user inbox queries stay exact in a shared store.
511 async fn user(store: &Store, name: &str) -> String {470 async fn user(store: &Store, name: &str) -> String {
512 store471 store
513 .create_user(name, None, "hash", false)472 .create_user(name, None, "hash", false)
crates/forge-core/src/store/notifications_extra.rsmodified+0 -5
@@ -1,9 +1,6 @@
1-//! Extra notification lookups for the inbox page: one row by id, scoped to its owner.
2-
3 use super::{Store, col_int, col_text, fetch_opt};1 use super::{Store, col_int, col_text, fetch_opt};
4 use crate::error::Result;2 use crate::error::Result;
5 3
6-/// Where an inbox row points: the repo, and the issue or pull it belongs to.
7 #[derive(Debug, Clone, PartialEq, Eq)]4 #[derive(Debug, Clone, PartialEq, Eq)]
8 pub struct NotificationTarget {5 pub struct NotificationTarget {
9 pub repo_id: String,6 pub repo_id: String,
@@ -14,8 +11,6 @@ pub struct NotificationTarget {
14 }11 }
15 12
16 impl Store {13 impl Store {
17- /// The inbox row `notification_id` when it belongs to `user_id`. Another user's row id, or an
18- /// unknown one, gives `None`.
19 pub async fn notification_target(14 pub async fn notification_target(
20 &self,15 &self,
21 user_id: &str,16 user_id: &str,
crates/forge-core/src/store/oci.rsmodified+0 -31
@@ -1,7 +1,3 @@
1-//! Container registry storage: the blobs a package may read, its manifests, the tags that name
2-//! them, and the references each manifest makes. Blob bytes are not here; the web layer writes and
3-//! deletes them under `oci/<hex>` in the blob store.
4-
5 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id};1 use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, missing_row, new_id};
6 use crate::error::{Error, Result};2 use crate::error::{Error, Result};
7 use crate::packages::{OciManifest, OciTag};3 use crate::packages::{OciManifest, OciTag};
@@ -26,12 +22,8 @@ fn to_u64(value: i64) -> Result<u64> {
26 }22 }
27 23
28 impl Store {24 impl Store {
29- /// Records that `package_id` may read the blob `digest` of `size` bytes. Linking a digest the
30- /// package already has changes nothing.
31 pub async fn oci_link_blob(&self, package_id: &str, digest: &str, size: u64) -> Result<()> {25 pub async fn oci_link_blob(&self, package_id: &str, digest: &str, size: u64) -> Result<()> {
32 let conn = self.inner.conn.lock().await;26 let conn = self.inner.conn.lock().await;
33- // A link made again starts its grace period over: the sweep keeps a recent link (see
34- // `oci_sweep_unreferenced`), and the push that made it is still on its way to a manifest.
35 conn.execute(27 conn.execute(
36 "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4) \28 "INSERT INTO oci_blobs (package_id, digest, size, created_at) VALUES (?1, ?2, ?3, ?4) \
37 ON CONFLICT(package_id, digest) DO UPDATE SET size = excluded.size, \29 ON CONFLICT(package_id, digest) DO UPDATE SET size = excluded.size, \
@@ -48,7 +40,6 @@ impl Store {
48 Ok(())40 Ok(())
49 }41 }
50 42
51- /// The size of blob `digest` as `package_id` links it, or `None` when it does not.
52 pub async fn oci_blob_size(&self, package_id: &str, digest: &str) -> Result<Option<u64>> {43 pub async fn oci_blob_size(&self, package_id: &str, digest: &str) -> Result<Option<u64>> {
53 let conn = self.read_conn().await;44 let conn = self.read_conn().await;
54 let size = fetch_opt(45 let size = fetch_opt(
@@ -61,7 +52,6 @@ impl Store {
61 size.map(to_u64).transpose()52 size.map(to_u64).transpose()
62 }53 }
63 54
64- /// True when any package links `digest`. Its bytes are kept while this holds.
65 pub async fn oci_digest_linked(&self, digest: &str) -> Result<bool> {55 pub async fn oci_digest_linked(&self, digest: &str) -> Result<bool> {
66 let conn = self.read_conn().await;56 let conn = self.read_conn().await;
67 let count = fetch_opt(57 let count = fetch_opt(
@@ -74,8 +64,6 @@ impl Store {
74 Ok(count.unwrap_or(0) > 0)64 Ok(count.unwrap_or(0) > 0)
75 }65 }
76 66
77- /// Stores a manifest of `package_id` under `digest`, with the digests it refers to. A manifest
78- /// already stored under that digest is kept as it is.
79 pub async fn oci_put_manifest(67 pub async fn oci_put_manifest(
80 &self,68 &self,
81 package_id: &str,69 package_id: &str,
@@ -119,7 +107,6 @@ impl Store {
119 Ok(manifest)107 Ok(manifest)
120 }108 }
121 109
122- /// The manifest of `package_id` stored under `digest`.
123 pub async fn oci_manifest(110 pub async fn oci_manifest(
124 &self,111 &self,
125 package_id: &str,112 package_id: &str,
@@ -138,7 +125,6 @@ impl Store {
138 .await125 .await
139 }126 }
140 127
141- /// The manifest the tag `tag` of `package_id` points at.
142 pub async fn oci_tag_manifest(128 pub async fn oci_tag_manifest(
143 &self,129 &self,
144 package_id: &str,130 package_id: &str,
@@ -156,7 +142,6 @@ impl Store {
156 .await142 .await
157 }143 }
158 144
159- /// Points `tag` of `package_id` at `manifest_id`, replacing any earlier target.
160 pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> {145 pub async fn oci_set_tag(&self, package_id: &str, tag: &str, manifest_id: &str) -> Result<()> {
161 let conn = self.inner.conn.lock().await;146 let conn = self.inner.conn.lock().await;
162 conn.execute(147 conn.execute(
@@ -175,8 +160,6 @@ impl Store {
175 Ok(())160 Ok(())
176 }161 }
177 162
178- /// Removes `tag` from `package_id`. Returns the manifest id it pointed at, or `None` when the
179- /// tag did not exist.
180 pub async fn oci_delete_tag(&self, package_id: &str, tag: &str) -> Result<Option<String>> {163 pub async fn oci_delete_tag(&self, package_id: &str, tag: &str) -> Result<Option<String>> {
181 let manifest_id = {164 let manifest_id = {
182 let conn = self.read_conn().await;165 let conn = self.read_conn().await;
@@ -201,7 +184,6 @@ impl Store {
201 Ok(Some(manifest_id))184 Ok(Some(manifest_id))
202 }185 }
203 186
204- /// How many tags point at a manifest.
205 pub async fn oci_manifest_tag_count(&self, manifest_id: &str) -> Result<u64> {187 pub async fn oci_manifest_tag_count(&self, manifest_id: &str) -> Result<u64> {
206 let conn = self.read_conn().await;188 let conn = self.read_conn().await;
207 let count = fetch_opt(189 let count = fetch_opt(
@@ -214,8 +196,6 @@ impl Store {
214 to_u64(count.unwrap_or(0))196 to_u64(count.unwrap_or(0))
215 }197 }
216 198
217- /// True when a manifest of `package_id` names `digest`: an index names its children, and a
218- /// manifest names its blobs.
219 pub async fn oci_digest_referenced(&self, package_id: &str, digest: &str) -> Result<bool> {199 pub async fn oci_digest_referenced(&self, package_id: &str, digest: &str) -> Result<bool> {
220 let conn = self.read_conn().await;200 let conn = self.read_conn().await;
221 let count = fetch_opt(201 let count = fetch_opt(
@@ -229,7 +209,6 @@ impl Store {
229 Ok(count.unwrap_or(0) > 0)209 Ok(count.unwrap_or(0) > 0)
230 }210 }
231 211
232- /// Removes a manifest by id. Its tags and references go with it.
233 pub async fn oci_delete_manifest(&self, manifest_id: &str) -> Result<()> {212 pub async fn oci_delete_manifest(&self, manifest_id: &str) -> Result<()> {
234 let conn = self.inner.conn.lock().await;213 let conn = self.inner.conn.lock().await;
235 conn.execute(214 conn.execute(
@@ -241,8 +220,6 @@ impl Store {
241 Ok(())220 Ok(())
242 }221 }
243 222
244- /// Tag names of `package_id` after `last` (empty for the first page), in order, at most
245- /// `limit` of them.
246 pub async fn oci_tag_names(223 pub async fn oci_tag_names(
247 &self,224 &self,
248 package_id: &str,225 package_id: &str,
@@ -263,7 +240,6 @@ impl Store {
263 .await240 .await
264 }241 }
265 242
266- /// Every tag of `package_id`, most recently updated first, with its manifest.
267 pub async fn oci_tags(&self, package_id: &str) -> Result<Vec<OciTag>> {243 pub async fn oci_tags(&self, package_id: &str) -> Result<Vec<OciTag>> {
268 let conn = self.read_conn().await;244 let conn = self.read_conn().await;
269 fetch_all(245 fetch_all(
@@ -286,12 +262,6 @@ impl Store {
286 .await262 .await
287 }263 }
288 264
289- /// The sweep of garbage collection for one package (mark and sweep). Drops every blob link of
290- /// `package_id` that no manifest of the package refers to and that was made before
291- /// `linked_before`, and returns the digests dropped. A newer link is a push whose manifest is
292- /// not yet PUT, so it is kept. An open upload session names no digest until it finishes, and
293- /// finishing links the blob with a fresh stamp, so the grace period covers sessions too.
294- /// The caller deletes the bytes of each digest that no package links any more.
295 pub async fn oci_sweep_unreferenced(265 pub async fn oci_sweep_unreferenced(
296 &self,266 &self,
297 package_id: &str,267 package_id: &str,
@@ -322,7 +292,6 @@ impl Store {
322 Ok(unreferenced)292 Ok(unreferenced)
323 }293 }
324 294
325- /// Removes the link of `digest` from `package_id`. Returns true when there was one.
326 pub async fn oci_unlink_blob(&self, package_id: &str, digest: &str) -> Result<bool> {295 pub async fn oci_unlink_blob(&self, package_id: &str, digest: &str) -> Result<bool> {
327 let changed = {296 let changed = {
328 let conn = self.inner.conn.lock().await;297 let conn = self.inner.conn.lock().await;
crates/forge-core/src/store/orgs.rsmodified+0 -74
@@ -1,10 +1,3 @@
1-//! Organizations. An org is a `users` row with `kind = 'org'` (migration 0025), so it shares the
2-//! username namespace with people and `repos.owner_id` still points at `users(id)`. This module
3-//! holds the org rows, their members, their teams, and the role an org gives on its repos.
4-//!
5-//! An org never signs in: its password hash is `"!org"`, and every authentication path refuses
6-//! `kind = 'org'` (see `User::is_org`).
7-
8 use turso::{Connection, IntoParams};1 use turso::{Connection, IntoParams};
9 2
10 use super::finish;3 use super::finish;
@@ -19,11 +12,8 @@ use crate::names::validate_username;
19 use crate::store::user_delete::LAST_ORG_OWNER;12 use crate::store::user_delete::LAST_ORG_OWNER;
20 use crate::time::now_stamp;13 use crate::time::now_stamp;
21 14
22-/// Stored on org rows instead of a password hash. Not a PHC string, so `verify_password` is
23-/// always false.
24 const ORG_PASSWORD_HASH: &str = "!org";15 const ORG_PASSWORD_HASH: &str = "!org";
25 16
26-/// A member's role in an org. `Owner` gives admin on every repo the org owns.
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]17 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 pub enum OrgMemberRole {18 pub enum OrgMemberRole {
29 Owner,19 Owner,
@@ -47,7 +37,6 @@ impl OrgMemberRole {
47 }37 }
48 }38 }
49 39
50-/// What members get on the org's repos when no team says otherwise.
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]40 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 pub enum DefaultRepoRole {41 pub enum DefaultRepoRole {
53 None,42 None,
@@ -88,7 +77,6 @@ pub struct OrgSettings {
88 pub members_can_create_repos: bool,77 pub members_can_create_repos: bool,
89 }78 }
90 79
91-/// A team inside an org. Its role is what its members get on the repos it covers.
92 #[derive(Debug, Clone, PartialEq)]80 #[derive(Debug, Clone, PartialEq)]
93 pub struct Team {81 pub struct Team {
94 pub id: Id,82 pub id: Id,
@@ -96,7 +84,6 @@ pub struct Team {
96 pub name: String,84 pub name: String,
97 pub description: String,85 pub description: String,
98 pub role: Role,86 pub role: Role,
99- /// True when the team covers every repo the org owns, not only the linked ones.
100 pub all_repos: bool,87 pub all_repos: bool,
101 pub created_at: String,88 pub created_at: String,
102 }89 }
@@ -115,7 +102,6 @@ fn map_team(row: &turso::Row) -> Result<Team> {
115 })102 })
116 }103 }
117 104
118-/// The kind of a `users` row, or `NotFound` when there is none.
119 async fn kind_of(conn: &Connection, id: &str) -> Result<String> {105 async fn kind_of(conn: &Connection, id: &str) -> Result<String> {
120 fetch_opt(106 fetch_opt(
121 conn,107 conn,
@@ -127,7 +113,6 @@ async fn kind_of(conn: &Connection, id: &str) -> Result<String> {
127 .ok_or(Error::NotFound)113 .ok_or(Error::NotFound)
128 }114 }
129 115
130-/// Refuses unless `id` is an org row. Returns `NotFound` for a missing id.
131 async fn require_org(conn: &Connection, id: &str) -> Result<()> {116 async fn require_org(conn: &Connection, id: &str) -> Result<()> {
132 if kind_of(conn, id).await? == "org" {117 if kind_of(conn, id).await? == "org" {
133 Ok(())118 Ok(())
@@ -136,7 +121,6 @@ async fn require_org(conn: &Connection, id: &str) -> Result<()> {
136 }121 }
137 }122 }
138 123
139-/// Number of owners the org has. Used by the last-owner rules.
140 async fn owner_count(conn: &Connection, org_id: &str) -> Result<i64> {124 async fn owner_count(conn: &Connection, org_id: &str) -> Result<i64> {
141 fetch_opt(125 fetch_opt(
142 conn,126 conn,
@@ -162,7 +146,6 @@ async fn member_role(
162 .await146 .await
163 }147 }
164 148
165-/// The org a team belongs to. `NotFound` for an unknown team.
166 async fn team_org(conn: &Connection, team_id: &str) -> Result<Id> {149 async fn team_org(conn: &Connection, team_id: &str) -> Result<Id> {
167 fetch_opt(150 fetch_opt(
168 conn,151 conn,
@@ -181,8 +164,6 @@ async fn count<P: IntoParams>(conn: &Connection, sql: &str, params: P) -> Result
181 }164 }
182 165
183 impl Store {166 impl Store {
184- /// Creates an org named `name` (validated like a username) and makes `creator_id` its
185- /// owner, with the default org settings. Only a person can create an org.
186 pub async fn create_org(&self, name: &str, creator_id: &str) -> Result<User> {167 pub async fn create_org(&self, name: &str, creator_id: &str) -> Result<User> {
187 let (display, folded) = validate_username(name)?;168 let (display, folded) = validate_username(name)?;
188 let org_id = new_id();169 let org_id = new_id();
@@ -230,7 +211,6 @@ impl Store {
230 self.user_by_id(&org_id).await?.ok_or_else(missing_row)211 self.user_by_id(&org_id).await?.ok_or_else(missing_row)
231 }212 }
232 213
233- /// The org's settings. `NotFound` when `org_id` is not an org.
234 pub async fn org_settings(&self, org_id: &str) -> Result<OrgSettings> {214 pub async fn org_settings(&self, org_id: &str) -> Result<OrgSettings> {
235 let conn = self.read_conn().await;215 let conn = self.read_conn().await;
236 fetch_opt(216 fetch_opt(
@@ -265,7 +245,6 @@ impl Store {
265 Ok(())245 Ok(())
266 }246 }
267 247
268- /// Members of the org with their org role, owners first.
269 pub async fn org_members(&self, org_id: &str) -> Result<Vec<(User, OrgMemberRole)>> {248 pub async fn org_members(&self, org_id: &str) -> Result<Vec<(User, OrgMemberRole)>> {
270 let conn = self.read_conn().await;249 let conn = self.read_conn().await;
271 fetch_all(250 fetch_all(
@@ -291,8 +270,6 @@ impl Store {
291 member_role(&conn, org_id, user_id).await270 member_role(&conn, org_id, user_id).await
292 }271 }
293 272
294- /// Adds a person to the org. Refused for an org or an unknown user as the member, and for
295- /// someone already in the org.
296 pub async fn add_org_member(273 pub async fn add_org_member(
297 &self,274 &self,
298 org_id: &str,275 org_id: &str,
@@ -320,7 +297,6 @@ impl Store {
320 Ok(())297 Ok(())
321 }298 }
322 299
323- /// Changes a member's org role. Refuses to demote the last owner.
324 pub async fn set_org_member_role(300 pub async fn set_org_member_role(
325 &self,301 &self,
326 org_id: &str,302 org_id: &str,
@@ -355,7 +331,6 @@ impl Store {
355 finish(tx, outcome).await331 finish(tx, outcome).await
356 }332 }
357 333
358- /// Removes a member from the org and from its teams. Refuses to remove the last owner.
359 pub async fn remove_org_member(&self, org_id: &str, user_id: &str) -> Result<()> {334 pub async fn remove_org_member(&self, org_id: &str, user_id: &str) -> Result<()> {
360 let conn = self.inner.conn.lock().await;335 let conn = self.inner.conn.lock().await;
361 let tx = conn.unchecked_transaction().await.map_err(db_err)?;336 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -385,7 +360,6 @@ impl Store {
385 finish(tx, outcome).await360 finish(tx, outcome).await
386 }361 }
387 362
388- /// The orgs `user_id` belongs to, with their role there.
389 pub async fn orgs_for_user(&self, user_id: &str) -> Result<Vec<(User, OrgMemberRole)>> {363 pub async fn orgs_for_user(&self, user_id: &str) -> Result<Vec<(User, OrgMemberRole)>> {
390 let conn = self.read_conn().await;364 let conn = self.read_conn().await;
391 fetch_all(365 fetch_all(
@@ -402,7 +376,6 @@ impl Store {
402 .await376 .await
403 }377 }
404 378
405- /// Every organization, by name. Used by the explore page.
406 pub async fn list_orgs(&self) -> Result<Vec<User>> {379 pub async fn list_orgs(&self) -> Result<Vec<User>> {
407 let conn = self.read_conn().await;380 let conn = self.read_conn().await;
408 fetch_all(381 fetch_all(
@@ -414,7 +387,6 @@ impl Store {
414 .await387 .await
415 }388 }
416 389
417- /// Deletes an org with its settings, members and teams. Refused while the org owns repos.
418 pub async fn delete_org(&self, org_id: &str) -> Result<()> {390 pub async fn delete_org(&self, org_id: &str) -> Result<()> {
419 let conn = self.inner.conn.lock().await;391 let conn = self.inner.conn.lock().await;
420 let tx = conn.unchecked_transaction().await.map_err(db_err)?;392 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -444,7 +416,6 @@ impl Store {
444 finish(tx, outcome).await416 finish(tx, outcome).await
445 }417 }
446 418
447- /// The team `team_id`, if it exists.
448 pub async fn team_by_id(&self, team_id: &str) -> Result<Option<Team>> {419 pub async fn team_by_id(&self, team_id: &str) -> Result<Option<Team>> {
449 let conn = self.read_conn().await;420 let conn = self.read_conn().await;
450 fetch_opt(421 fetch_opt(
@@ -456,7 +427,6 @@ impl Store {
456 .await427 .await
457 }428 }
458 429
459- /// Every team of the org, by name.
460 pub async fn teams_for_org(&self, org_id: &str) -> Result<Vec<Team>> {430 pub async fn teams_for_org(&self, org_id: &str) -> Result<Vec<Team>> {
461 let conn = self.read_conn().await;431 let conn = self.read_conn().await;
462 fetch_all(432 fetch_all(
@@ -468,8 +438,6 @@ impl Store {
468 .await438 .await
469 }439 }
470 440
471- /// Creates a team in an org. The name is validated like a username and must be unique
472- /// within the org.
473 pub async fn create_team(441 pub async fn create_team(
474 &self,442 &self,
475 org_id: &str,443 org_id: &str,
@@ -510,7 +478,6 @@ impl Store {
510 })478 })
511 }479 }
512 480
513- /// Changes a team's name, description, role and repo coverage.
514 pub async fn update_team(481 pub async fn update_team(
515 &self,482 &self,
516 team_id: &str,483 team_id: &str,
@@ -542,7 +509,6 @@ impl Store {
542 Ok(())509 Ok(())
543 }510 }
544 511
545- /// Deletes a team with its members and repo links.
546 pub async fn delete_team(&self, team_id: &str) -> Result<()> {512 pub async fn delete_team(&self, team_id: &str) -> Result<()> {
547 let conn = self.inner.conn.lock().await;513 let conn = self.inner.conn.lock().await;
548 let tx = conn.unchecked_transaction().await.map_err(db_err)?;514 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -563,7 +529,6 @@ impl Store {
563 finish(tx, outcome).await529 finish(tx, outcome).await
564 }530 }
565 531
566- /// Adds an org member to a team. Refused for someone outside the org.
567 pub async fn add_team_member(&self, team_id: &str, user_id: &str) -> Result<()> {532 pub async fn add_team_member(&self, team_id: &str, user_id: &str) -> Result<()> {
568 let conn = self.inner.conn.lock().await;533 let conn = self.inner.conn.lock().await;
569 let tx = conn.unchecked_transaction().await.map_err(db_err)?;534 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -586,7 +551,6 @@ impl Store {
586 finish(tx, outcome).await551 finish(tx, outcome).await
587 }552 }
588 553
589- /// Removes a user from a team. `false` when they were not in it.
590 pub async fn remove_team_member(&self, team_id: &str, user_id: &str) -> Result<bool> {554 pub async fn remove_team_member(&self, team_id: &str, user_id: &str) -> Result<bool> {
591 let conn = self.inner.conn.lock().await;555 let conn = self.inner.conn.lock().await;
592 let n = conn556 let n = conn
@@ -599,7 +563,6 @@ impl Store {
599 Ok(n > 0)563 Ok(n > 0)
600 }564 }
601 565
602- /// Members of a team.
603 pub async fn team_members(&self, team_id: &str) -> Result<Vec<User>> {566 pub async fn team_members(&self, team_id: &str) -> Result<Vec<User>> {
604 let conn = self.read_conn().await;567 let conn = self.read_conn().await;
605 fetch_all(568 fetch_all(
@@ -614,7 +577,6 @@ impl Store {
614 .await577 .await
615 }578 }
616 579
617- /// Links a repo to a team. The repo must be owned by the team's org.
618 pub async fn add_team_repo(&self, team_id: &str, repo_id: &str) -> Result<()> {580 pub async fn add_team_repo(&self, team_id: &str, repo_id: &str) -> Result<()> {
619 let conn = self.inner.conn.lock().await;581 let conn = self.inner.conn.lock().await;
620 let tx = conn.unchecked_transaction().await.map_err(db_err)?;582 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -643,7 +605,6 @@ impl Store {
643 finish(tx, outcome).await605 finish(tx, outcome).await
644 }606 }
645 607
646- /// Unlinks a repo from a team. `false` when it was not linked.
647 pub async fn remove_team_repo(&self, team_id: &str, repo_id: &str) -> Result<bool> {608 pub async fn remove_team_repo(&self, team_id: &str, repo_id: &str) -> Result<bool> {
648 let conn = self.inner.conn.lock().await;609 let conn = self.inner.conn.lock().await;
649 let n = conn610 let n = conn
@@ -656,7 +617,6 @@ impl Store {
656 Ok(n > 0)617 Ok(n > 0)
657 }618 }
658 619
659- /// Repos linked to a team (not the `all_repos` coverage), by name.
660 pub async fn team_repos(&self, team_id: &str) -> Result<Vec<Repo>> {620 pub async fn team_repos(&self, team_id: &str) -> Result<Vec<Repo>> {
661 let conn = self.read_conn().await;621 let conn = self.read_conn().await;
662 fetch_all(622 fetch_all(
@@ -671,12 +631,6 @@ impl Store {
671 .await631 .await
672 }632 }
673 633
674- /// The role `user_id` gets on `repo_id` through the org `org_id`, or `None`.
675- ///
676- /// - Not an org member, or the repo is not owned by this org: `None`.
677- /// - Owner: `Admin`.
678- /// - Member: the higher of the org's `default_repo_role` and the role of every team the
679- /// member is in that covers the repo (`all_repos`, or linked to it).
680 pub async fn org_repo_role(634 pub async fn org_repo_role(
681 &self,635 &self,
682 org_id: &str,636 org_id: &str,
@@ -748,12 +702,10 @@ mod tests {
748 (org, repo)702 (org, repo)
749 }703 }
750 704
751- /// Scenarios share one store. Each has its own people and org names.
752 #[tokio::test]705 #[tokio::test]
753 async fn org_creation_and_owner_rules() {706 async fn org_creation_and_owner_rules() {
754 let (_dir, store) = store().await;707 let (_dir, store) = store().await;
755 708
756- // the creator becomes an owner with default settings
757 let tahinli = person(&store, "tahinli").await;709 let tahinli = person(&store, "tahinli").await;
758 let org = store.create_org("Acme", &tahinli.id).await.unwrap();710 let org = store.create_org("Acme", &tahinli.id).await.unwrap();
759 assert!(org.is_org());711 assert!(org.is_org());
@@ -771,13 +723,11 @@ mod tests {
771 members_can_create_repos: true,723 members_can_create_repos: true,
772 }724 }
773 );725 );
774- // The org shares the username namespace with people.
775 assert!(store.create_org("tahinli", &tahinli.id).await.is_err());726 assert!(store.create_org("tahinli", &tahinli.id).await.is_err());
776 assert!(store.create_user("acme", None, "h", false).await.is_err());727 assert!(store.create_user("acme", None, "h", false).await.is_err());
777 assert!(store.create_org("org", &tahinli.id).await.is_err());728 assert!(store.create_org("org", &tahinli.id).await.is_err());
778 assert!(store.create_org("bad name", &tahinli.id).await.is_err());729 assert!(store.create_org("bad name", &tahinli.id).await.is_err());
779 730
780- // only a person can create an org or join one
781 let ada = person(&store, "ada").await;731 let ada = person(&store, "ada").await;
782 let umbrella = store.create_org("umbrella", &ada.id).await.unwrap();732 let umbrella = store.create_org("umbrella", &ada.id).await.unwrap();
783 assert!(matches!(733 assert!(matches!(
@@ -792,7 +742,6 @@ mod tests {
792 Err(Error::Invalid(_))742 Err(Error::Invalid(_))
793 ));743 ));
794 744
795- // the last owner cannot be removed or demoted
796 let grace = person(&store, "grace").await;745 let grace = person(&store, "grace").await;
797 let hopper = person(&store, "hopper").await;746 let hopper = person(&store, "hopper").await;
798 let initech = store.create_org("initech", &grace.id).await.unwrap();747 let initech = store.create_org("initech", &grace.id).await.unwrap();
@@ -810,7 +759,6 @@ mod tests {
810 .await,759 .await,
811 Err(Error::Conflict(_))760 Err(Error::Conflict(_))
812 ));761 ));
813- // With a second owner, the first may go.
814 store762 store
815 .set_org_member_role(&initech.id, &hopper.id, OrgMemberRole::Owner)763 .set_org_member_role(&initech.id, &hopper.id, OrgMemberRole::Owner)
816 .await764 .await
@@ -835,7 +783,6 @@ mod tests {
835 assert_eq!(members.len(), 1);783 assert_eq!(members.len(), 1);
836 assert_eq!(members[0].1, OrgMemberRole::Owner);784 assert_eq!(members[0].1, OrgMemberRole::Owner);
837 785
838- // deleting the last owner of an org is refused
839 let linus = person(&store, "linus").await;786 let linus = person(&store, "linus").await;
840 let ken = person(&store, "ken").await;787 let ken = person(&store, "ken").await;
841 let hooli = store.create_org("hooli", &linus.id).await.unwrap();788 let hooli = store.create_org("hooli", &linus.id).await.unwrap();
@@ -847,7 +794,6 @@ mod tests {
847 "{refused:?}"794 "{refused:?}"
848 );795 );
849 assert!(store.user_by_id(&linus.id).await.unwrap().is_some());796 assert!(store.user_by_id(&linus.id).await.unwrap().is_some());
850- // A second owner makes the deletion allowed.
851 store797 store
852 .add_org_member(&hooli.id, &ken.id, OrgMemberRole::Owner)798 .add_org_member(&hooli.id, &ken.id, OrgMemberRole::Owner)
853 .await799 .await
@@ -859,7 +805,6 @@ mod tests {
859 Some(OrgMemberRole::Owner)805 Some(OrgMemberRole::Owner)
860 );806 );
861 807
862- // an org cannot be deleted as a user, and delete_org needs no repos
863 let margaret = person(&store, "margaret").await;808 let margaret = person(&store, "margaret").await;
864 let (lambda, repo) = org_with_repo(&store, &margaret, "lambda").await;809 let (lambda, repo) = org_with_repo(&store, &margaret, "lambda").await;
865 assert!(matches!(810 assert!(matches!(
@@ -879,8 +824,6 @@ mod tests {
879 ));824 ));
880 }825 }
881 826
882- /// Repo roles an org grants through its default role and teams, and the
883- /// lookup of an org-owned repo by owner and name.
884 #[tokio::test]827 #[tokio::test]
885 async fn org_repo_roles_and_lookup() {828 async fn org_repo_roles_and_lookup() {
886 let (_dir, store) = store().await;829 let (_dir, store) = store().await;
@@ -897,7 +840,6 @@ mod tests {
897 .await840 .await
898 .unwrap();841 .unwrap();
899 842
900- // Owner gives admin, on every org-owned repo.
901 assert_eq!(843 assert_eq!(
902 store844 store
903 .org_repo_role(&org.id, &frank.id, &repo.id)845 .org_repo_role(&org.id, &frank.id, &repo.id)
@@ -905,7 +847,6 @@ mod tests {
905 .unwrap(),847 .unwrap(),
906 Some(Role::Admin)848 Some(Role::Admin)
907 );849 );
908- // A member with the default read role.
909 assert_eq!(850 assert_eq!(
910 store851 store
911 .org_repo_role(&org.id, &bob.id, &repo.id)852 .org_repo_role(&org.id, &bob.id, &repo.id)
@@ -913,7 +854,6 @@ mod tests {
913 .unwrap(),854 .unwrap(),
914 Some(Role::Read)855 Some(Role::Read)
915 );856 );
916- // A repo the org does not own gets nothing from the org.
917 assert_eq!(857 assert_eq!(
918 store858 store
919 .org_repo_role(&org.id, &frank.id, &other.id)859 .org_repo_role(&org.id, &frank.id, &other.id)
@@ -921,7 +861,6 @@ mod tests {
921 .unwrap(),861 .unwrap(),
922 None862 None
923 );863 );
924- // A stranger gets nothing.
925 let carol = person(&store, "carol").await;864 let carol = person(&store, "carol").await;
926 assert_eq!(865 assert_eq!(
927 store866 store
@@ -931,7 +870,6 @@ mod tests {
931 None870 None
932 );871 );
933 872
934- // Default none removes the member's base role.
935 store873 store
936 .set_org_settings(874 .set_org_settings(
937 &org.id,875 &org.id,
@@ -950,7 +888,6 @@ mod tests {
950 None888 None
951 );889 );
952 890
953- // A team linked to the repo raises the member; the max wins.
954 let team = store891 let team = store
955 .create_team(&org.id, "core", "", Role::Maintain, false)892 .create_team(&org.id, "core", "", Role::Maintain, false)
956 .await893 .await
@@ -971,7 +908,6 @@ mod tests {
971 .unwrap(),908 .unwrap(),
972 Some(Role::Maintain)909 Some(Role::Maintain)
973 );910 );
974- // A team with all_repos covers the repo too, and a lower team never lowers it.
975 let readers = store911 let readers = store
976 .create_team(&org.id, "readers", "", Role::Read, true)912 .create_team(&org.id, "readers", "", Role::Read, true)
977 .await913 .await
@@ -984,7 +920,6 @@ mod tests {
984 .unwrap(),920 .unwrap(),
985 Some(Role::Maintain)921 Some(Role::Maintain)
986 );922 );
987- // Not in the team, so not covered: only the team's repos count.
988 store.remove_team_member(&team.id, &bob.id).await.unwrap();923 store.remove_team_member(&team.id, &bob.id).await.unwrap();
989 assert_eq!(924 assert_eq!(
990 store925 store
@@ -993,7 +928,6 @@ mod tests {
993 .unwrap(),928 .unwrap(),
994 Some(Role::Read)929 Some(Role::Read)
995 );930 );
996- // An org that is not an org.
997 assert_eq!(931 assert_eq!(
998 store932 store
999 .org_repo_role(&frank.id, &frank.id, &repo.id)933 .org_repo_role(&frank.id, &frank.id, &repo.id)
@@ -1002,7 +936,6 @@ mod tests {
1002 None936 None
1003 );937 );
1004 938
1005- // An org-owned repo is found by its owner and name.
1006 let dana = person(&store, "dana").await;939 let dana = person(&store, "dana").await;
1007 let (soylent, soylent_repo) = org_with_repo(&store, &dana, "soylent").await;940 let (soylent, soylent_repo) = org_with_repo(&store, &dana, "soylent").await;
1008 let found = store941 let found = store
@@ -1015,8 +948,6 @@ mod tests {
1015 assert_eq!(found.owner_name, "soylent");948 assert_eq!(found.owner_name, "soylent");
1016 }949 }
1017 950
1018- /// The org listing, teams and their members and repo links, and the orgs a
1019- /// user belongs to. The listing comes first because it starts empty.
1020 #[tokio::test]951 #[tokio::test]
1021 async fn teams_memberships_and_org_listing() {952 async fn teams_memberships_and_org_listing() {
1022 let (_dir, store) = store().await;953 let (_dir, store) = store().await;
@@ -1033,7 +964,6 @@ mod tests {
1033 .collect();964 .collect();
1034 assert_eq!(names, vec![acme.username.clone()]);965 assert_eq!(names, vec![acme.username.clone()]);
1035 966
1036- // teams
1037 let nina = person(&store, "nina").await;967 let nina = person(&store, "nina").await;
1038 let (org, repo) = org_with_repo(&store, &nina, "wayne").await;968 let (org, repo) = org_with_repo(&store, &nina, "wayne").await;
1039 let theirs = store969 let theirs = store
@@ -1066,7 +996,6 @@ mod tests {
1066 assert!(loaded.all_repos);996 assert!(loaded.all_repos);
1067 assert_eq!(store.teams_for_org(&org.id).await.unwrap().len(), 1);997 assert_eq!(store.teams_for_org(&org.id).await.unwrap().len(), 1);
1068 998
1069- // Only org members join teams.
1070 let pam = person(&store, "pam").await;999 let pam = person(&store, "pam").await;
1071 assert!(matches!(1000 assert!(matches!(
1072 store.add_team_member(&team.id, &pam.id).await,1001 store.add_team_member(&team.id, &pam.id).await,
@@ -1076,7 +1005,6 @@ mod tests {
1076 assert!(store.add_team_member(&team.id, &oscar.id).await.is_err());1005 assert!(store.add_team_member(&team.id, &oscar.id).await.is_err());
1077 assert_eq!(store.team_members(&team.id).await.unwrap().len(), 1);1006 assert_eq!(store.team_members(&team.id).await.unwrap().len(), 1);
1078 1007
1079- // Only repos the org owns can be linked.
1080 assert!(matches!(1008 assert!(matches!(
1081 store.add_team_repo(&team.id, &theirs.id).await,1009 store.add_team_repo(&team.id, &theirs.id).await,
1082 Err(Error::Invalid(_))1010 Err(Error::Invalid(_))
@@ -1088,7 +1016,6 @@ mod tests {
1088 assert!(store.remove_team_repo(&team.id, &repo.id).await.unwrap());1016 assert!(store.remove_team_repo(&team.id, &repo.id).await.unwrap());
1089 assert!(!store.remove_team_repo(&team.id, &repo.id).await.unwrap());1017 assert!(!store.remove_team_repo(&team.id, &repo.id).await.unwrap());
1090 1018
1091- // Deleting a team removes its membership and links, not the users or the repos.
1092 store.add_team_repo(&team.id, &repo.id).await.unwrap();1019 store.add_team_repo(&team.id, &repo.id).await.unwrap();
1093 store.delete_team(&team.id).await.unwrap();1020 store.delete_team(&team.id).await.unwrap();
1094 assert!(store.team_by_id(&team.id).await.unwrap().is_none());1021 assert!(store.team_by_id(&team.id).await.unwrap().is_none());
@@ -1100,7 +1027,6 @@ mod tests {
1100 Err(Error::NotFound)1027 Err(Error::NotFound)
1101 ));1028 ));
1102 1029
1103- // orgs a user belongs to
1104 let quinn = person(&store, "quinn").await;1030 let quinn = person(&store, "quinn").await;
1105 let rita = person(&store, "rita").await;1031 let rita = person(&store, "rita").await;
1106 let tyrell = store.create_org("tyrell", &quinn.id).await.unwrap();1032 let tyrell = store.create_org("tyrell", &quinn.id).await.unwrap();
crates/forge-core/src/store/packages.rsmodified+0 -22
@@ -1,6 +1,3 @@
1-//! Package storage: packages, their versions and the link to a repo. Blob bytes are not here;
2-//! the web layer writes and deletes them, under the ids this module returns.
3-
4 use turso::{Row, Value};1 use turso::{Row, Value};
5 2
6 use super::{3 use super::{
@@ -17,7 +14,6 @@ const PACKAGE_COLS: &str = "p.id, p.owner_id, p.kind, p.name, p.name_key, p.repo
17 const VERSION_COLS: &str = "id, package_id, version, yanked, checksum, size, index_json, \14 const VERSION_COLS: &str = "id, package_id, version, yanked, checksum, size, index_json, \
18 description, readme, publisher_id, created_at";15 description, readme, publisher_id, created_at";
19 16
20-/// Newest first, by publish time.
21 const VERSION_ORDER: &str = "created_at DESC, id DESC";17 const VERSION_ORDER: &str = "created_at DESC, id DESC";
22 18
23 fn map_package(row: &Row) -> Result<Package> {19 fn map_package(row: &Row) -> Result<Package> {
@@ -63,8 +59,6 @@ fn map_version(row: &Row) -> Result<PackageVersion> {
63 }59 }
64 60
65 impl Store {61 impl Store {
66- /// The package `name_key` of `owner_id` in `kind`, created when it does not exist yet. The
67- /// name as first published is kept.
68 pub async fn ensure_package(62 pub async fn ensure_package(
69 &self,63 &self,
70 owner_id: &str,64 owner_id: &str,
@@ -94,7 +88,6 @@ impl Store {
94 .ok_or_else(missing_row)88 .ok_or_else(missing_row)
95 }89 }
96 90
97- /// One package by id.
98 pub async fn package(&self, id: &str) -> Result<Option<Package>> {91 pub async fn package(&self, id: &str) -> Result<Option<Package>> {
99 let conn = self.read_conn().await;92 let conn = self.read_conn().await;
100 fetch_opt(93 fetch_opt(
@@ -106,7 +99,6 @@ impl Store {
106 .await99 .await
107 }100 }
108 101
109- /// The package of `owner_id` called `name_key` in `kind`.
110 pub async fn package_by_name(102 pub async fn package_by_name(
111 &self,103 &self,
112 owner_id: &str,104 owner_id: &str,
@@ -126,8 +118,6 @@ impl Store {
126 .await118 .await
127 }119 }
128 120
129- /// Every package of an owner in `kind`, by name, with its version count and newest version. For
130- /// an `oci` image the versions are its tags, newest first by update, and it has no description.
131 pub async fn list_packages(&self, owner_id: &str, kind: &str) -> Result<Vec<PackageSummary>> {121 pub async fn list_packages(&self, owner_id: &str, kind: &str) -> Result<Vec<PackageSummary>> {
132 let conn = self.read_conn().await;122 let conn = self.read_conn().await;
133 fetch_all(123 fetch_all(
@@ -153,7 +143,6 @@ impl Store {
153 .await143 .await
154 }144 }
155 145
156- /// The packages linked to a repo, by name.
157 pub async fn packages_for_repo(&self, repo_id: &str) -> Result<Vec<Package>> {146 pub async fn packages_for_repo(&self, repo_id: &str) -> Result<Vec<Package>> {
158 let conn = self.read_conn().await;147 let conn = self.read_conn().await;
159 fetch_all(148 fetch_all(
@@ -167,8 +156,6 @@ impl Store {
167 .await156 .await
168 }157 }
169 158
170- /// True when the owner has at least one private package in any kind. A registry with one
171- /// must ask every client for credentials.
172 pub async fn owner_has_private_packages(&self, owner_id: &str) -> Result<bool> {159 pub async fn owner_has_private_packages(&self, owner_id: &str) -> Result<bool> {
173 let conn = self.read_conn().await;160 let conn = self.read_conn().await;
174 let count = fetch_opt(161 let count = fetch_opt(
@@ -181,7 +168,6 @@ impl Store {
181 Ok(count.unwrap_or(0) > 0)168 Ok(count.unwrap_or(0) > 0)
182 }169 }
183 170
184- /// Links a package to a repo on this forge, or unlinks it with `None`.
185 pub async fn set_package_repo(&self, package_id: &str, repo_id: Option<&str>) -> Result<()> {171 pub async fn set_package_repo(&self, package_id: &str, repo_id: Option<&str>) -> Result<()> {
186 let conn = self.inner.conn.lock().await;172 let conn = self.inner.conn.lock().await;
187 conn.execute(173 conn.execute(
@@ -197,7 +183,6 @@ impl Store {
197 Ok(())183 Ok(())
198 }184 }
199 185
200- /// Sets whether a package is private.
201 pub async fn set_package_private(&self, package_id: &str, private: bool) -> Result<()> {186 pub async fn set_package_private(&self, package_id: &str, private: bool) -> Result<()> {
202 let conn = self.inner.conn.lock().await;187 let conn = self.inner.conn.lock().await;
203 conn.execute(188 conn.execute(
@@ -209,7 +194,6 @@ impl Store {
209 Ok(())194 Ok(())
210 }195 }
211 196
212- /// The versions of a package, newest first, yanked ones included.
213 pub async fn package_versions(&self, package_id: &str) -> Result<Vec<PackageVersion>> {197 pub async fn package_versions(&self, package_id: &str) -> Result<Vec<PackageVersion>> {
214 let conn = self.read_conn().await;198 let conn = self.read_conn().await;
215 fetch_all(199 fetch_all(
@@ -224,7 +208,6 @@ impl Store {
224 .await208 .await
225 }209 }
226 210
227- /// One version of a package.
228 pub async fn package_version(211 pub async fn package_version(
229 &self,212 &self,
230 package_id: &str,213 package_id: &str,
@@ -243,9 +226,6 @@ impl Store {
243 .await226 .await
244 }227 }
245 228
246- /// Adds a version row. A version that is already published is `Conflict`. The row is
247- /// written before the bytes, so the caller removes it with [`Store::delete_package_version`]
248- /// when the blob write fails.
249 pub async fn publish_package_version(229 pub async fn publish_package_version(
250 &self,230 &self,
251 new: &NewPackageVersion<'_>,231 new: &NewPackageVersion<'_>,
@@ -286,7 +266,6 @@ impl Store {
286 .ok_or_else(missing_row)266 .ok_or_else(missing_row)
287 }267 }
288 268
289- /// Removes a version row, for when its bytes could not be stored.
290 pub async fn delete_package_version(&self, package_id: &str, version: &str) -> Result<()> {269 pub async fn delete_package_version(&self, package_id: &str, version: &str) -> Result<()> {
291 let conn = self.inner.conn.lock().await;270 let conn = self.inner.conn.lock().await;
292 conn.execute(271 conn.execute(
@@ -298,7 +277,6 @@ impl Store {
298 Ok(())277 Ok(())
299 }278 }
300 279
301- /// Sets the yank state of a version. Returns false when the version does not exist.
302 pub async fn set_package_version_yanked(280 pub async fn set_package_version_yanked(
303 &self,281 &self,
304 package_id: &str,282 package_id: &str,
crates/forge-core/src/store/passkeys.rsmodified+0 -24
@@ -1,26 +1,17 @@
1-//! WebAuthn passkeys (migration 0058). The store keeps each credential as an opaque serialized
2-//! string; the web crate owns the format. Sign counts live inside that string, so an update
3-//! replaces it.
4-
5 use super::{1 use super::{
6 Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id,2 Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id,
7 };3 };
8 use crate::error::{Error, Result};4 use crate::error::{Error, Result};
9 use crate::time::now_stamp;5 use crate::time::now_stamp;
10 6
11-/// Most passkeys one account may hold.
12 pub const MAX_PASSKEYS: usize = 20;7 pub const MAX_PASSKEYS: usize = 20;
13-/// Longest passkey name, in characters.
14 pub const MAX_NAME_CHARS: usize = 40;8 pub const MAX_NAME_CHARS: usize = 40;
15 9
16-/// One registered passkey.
17 #[derive(Debug, Clone, PartialEq, Eq)]10 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub struct PasskeyRow {11 pub struct PasskeyRow {
19 pub id: String,12 pub id: String,
20 pub user_id: String,13 pub user_id: String,
21- /// Base64url credential id.
22 pub credential_id: String,14 pub credential_id: String,
23- /// The serialized credential.
24 pub passkey: String,15 pub passkey: String,
25 pub name: String,16 pub name: String,
26 pub created_at: String,17 pub created_at: String,
@@ -52,7 +43,6 @@ fn map_row(row: &turso::Row) -> Result<PasskeyRow> {
52 })43 })
53 }44 }
54 45
55-/// A trimmed passkey name, or the reason it is refused.
56 pub fn clean_name(name: &str) -> Result<String> {46 pub fn clean_name(name: &str) -> Result<String> {
57 let name = name.trim();47 let name = name.trim();
58 if name.is_empty()48 if name.is_empty()
@@ -67,7 +57,6 @@ pub fn clean_name(name: &str) -> Result<String> {
67 }57 }
68 58
69 impl Store {59 impl Store {
70- /// The user's passkeys, oldest first.
71 pub async fn list_passkeys(&self, user_id: &str) -> Result<Vec<PasskeyRow>> {60 pub async fn list_passkeys(&self, user_id: &str) -> Result<Vec<PasskeyRow>> {
72 let conn = self.read_conn().await;61 let conn = self.read_conn().await;
73 fetch_all(62 fetch_all(
@@ -84,7 +73,6 @@ impl Store {
84 count_passkeys(&conn, user_id).await73 count_passkeys(&conn, user_id).await
85 }74 }
86 75
87- /// The passkey with this credential id, whoever owns it.
88 pub async fn passkey_by_credential(&self, credential_id: &str) -> Result<Option<PasskeyRow>> {76 pub async fn passkey_by_credential(&self, credential_id: &str) -> Result<Option<PasskeyRow>> {
89 let conn = self.read_conn().await;77 let conn = self.read_conn().await;
90 fetch_opt(78 fetch_opt(
@@ -96,7 +84,6 @@ impl Store {
96 .await84 .await
97 }85 }
98 86
99- /// Stores a new passkey. Refused past `MAX_PASSKEYS` and for a credential id already stored.
100 pub async fn add_passkey(87 pub async fn add_passkey(
101 &self,88 &self,
102 user_id: &str,89 user_id: &str,
@@ -138,8 +125,6 @@ impl Store {
138 Ok(row)125 Ok(row)
139 }126 }
140 127
141- /// Records a sign-in: the updated serialized credential (with its new sign count) and the
142- /// time of use.
143 pub async fn touch_passkey(&self, id: &str, passkey: &str) -> Result<()> {128 pub async fn touch_passkey(&self, id: &str, passkey: &str) -> Result<()> {
144 let conn = self.inner.conn.lock().await;129 let conn = self.inner.conn.lock().await;
145 conn.execute(130 conn.execute(
@@ -151,7 +136,6 @@ impl Store {
151 Ok(())136 Ok(())
152 }137 }
153 138
154- /// Renames a passkey of `user_id`. Returns false when the user has no such passkey.
155 pub async fn rename_passkey(&self, user_id: &str, id: &str, name: &str) -> Result<bool> {139 pub async fn rename_passkey(&self, user_id: &str, id: &str, name: &str) -> Result<bool> {
156 let name = clean_name(name)?;140 let name = clean_name(name)?;
157 let conn = self.inner.conn.lock().await;141 let conn = self.inner.conn.lock().await;
@@ -165,8 +149,6 @@ impl Store {
165 Ok(n > 0)149 Ok(n > 0)
166 }150 }
167 151
168- /// Deletes a passkey of `user_id`. Returns false when the user has no such passkey, which is
169- /// also the answer for another account's passkey.
170 pub async fn delete_passkey(&self, user_id: &str, id: &str) -> Result<bool> {152 pub async fn delete_passkey(&self, user_id: &str, id: &str) -> Result<bool> {
171 let conn = self.inner.conn.lock().await;153 let conn = self.inner.conn.lock().await;
172 let n = conn154 let n = conn
@@ -179,7 +161,6 @@ impl Store {
179 Ok(n > 0)161 Ok(n > 0)
180 }162 }
181 163
182- /// Deletes every passkey of the user. Returns how many were removed.
183 pub async fn delete_all_passkeys(&self, user_id: &str) -> Result<u64> {164 pub async fn delete_all_passkeys(&self, user_id: &str) -> Result<u64> {
184 let conn = self.inner.conn.lock().await;165 let conn = self.inner.conn.lock().await;
185 conn.execute(166 conn.execute(
@@ -199,13 +180,11 @@ mod tests {
199 store.create_user(name, None, "x", false).await.unwrap().id180 store.create_user(name, None, "x", false).await.unwrap().id
200 }181 }
201 182
202- /// Scenarios share one store; each uses its own users and credential ids.
203 #[tokio::test]183 #[tokio::test]
204 async fn passkey_lifecycle_ownership_and_limits() {184 async fn passkey_lifecycle_ownership_and_limits() {
205 let dir = tempfile::tempdir().unwrap();185 let dir = tempfile::tempdir().unwrap();
206 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();186 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
207 187
208- // add, list, touch, rename, delete
209 let a = user(&store, "tahinli").await;188 let a = user(&store, "tahinli").await;
210 let row = store189 let row = store
211 .add_passkey(&a, "cred-1", "{\"n\":1}", " Laptop ")190 .add_passkey(&a, "cred-1", "{\"n\":1}", " Laptop ")
@@ -232,7 +211,6 @@ mod tests {
232 assert!(store.delete_passkey(&a, &row.id).await.unwrap());211 assert!(store.delete_passkey(&a, &row.id).await.unwrap());
233 assert_eq!(store.passkey_count(&a).await.unwrap(), 0);212 assert_eq!(store.passkey_count(&a).await.unwrap(), 0);
234 213
235- // other accounts cannot rename or delete
236 let c = user(&store, "carol").await;214 let c = user(&store, "carol").await;
237 let d = user(&store, "dave").await;215 let d = user(&store, "dave").await;
238 let row = store216 let row = store
@@ -243,7 +221,6 @@ mod tests {
243 assert!(!store.delete_passkey(&d, &row.id).await.unwrap());221 assert!(!store.delete_passkey(&d, &row.id).await.unwrap());
244 assert_eq!(store.list_passkeys(&c).await.unwrap()[0].name, "Laptop");222 assert_eq!(store.list_passkeys(&c).await.unwrap()[0].name, "Laptop");
245 223
246- // duplicate credential and the per-account limit are refused
247 let f = user(&store, "frank").await;224 let f = user(&store, "frank").await;
248 let g = user(&store, "gus").await;225 let g = user(&store, "gus").await;
249 store.add_passkey(&f, "cred-3", "{}", "One").await.unwrap();226 store.add_passkey(&f, "cred-3", "{}", "One").await.unwrap();
@@ -264,7 +241,6 @@ mod tests {
264 .is_err()241 .is_err()
265 );242 );
266 243
267- // delete all removes only that user's passkeys
268 let h = user(&store, "hana").await;244 let h = user(&store, "hana").await;
269 let i = user(&store, "ivan").await;245 let i = user(&store, "ivan").await;
270 store.add_passkey(&h, "cred-4", "{}", "One").await.unwrap();246 store.add_passkey(&h, "cred-4", "{}", "One").await.unwrap();
crates/forge-core/src/store/pinned.rsmodified+0 -15
@@ -1,6 +1,3 @@
1-//! Pinned issues: up to `MAX_PINNED` issues per repo, shown above the issue list. Only issues are
2-//! pinned, never pull requests. Repo deletion removes the rows in `issues::delete_repo_issue_rows`.
3-
4 use turso::Connection;1 use turso::Connection;
5 2
6 use super::issues::{ISSUE_COLS, map_issue};3 use super::issues::{ISSUE_COLS, map_issue};
@@ -9,7 +6,6 @@ use crate::error::{Error, Result};
9 use crate::issues::Issue;6 use crate::issues::Issue;
10 use crate::time::now_stamp;7 use crate::time::now_stamp;
11 8
12-/// Most issues one repo may pin.
13 pub const MAX_PINNED: usize = 3;9 pub const MAX_PINNED: usize = 3;
14 10
15 async fn is_pinned_on(conn: &Connection, repo_id: &str, issue_id: &str) -> Result<bool> {11 async fn is_pinned_on(conn: &Connection, repo_id: &str, issue_id: &str) -> Result<bool> {
@@ -24,9 +20,6 @@ async fn is_pinned_on(conn: &Connection, repo_id: &str, issue_id: &str) -> Resul
24 }20 }
25 21
26 impl Store {22 impl Store {
27- /// Pins an issue of this repo at the end of the list. Returns `true` when it was newly pinned
28- /// and `false` when it already was (pinning again changes nothing). A pull request or an issue
29- /// of another repo is `NotFound`. A repo that already has `MAX_PINNED` pins is `Invalid`.
30 pub async fn pin_issue(&self, repo_id: &str, issue_id: &str) -> Result<bool> {23 pub async fn pin_issue(&self, repo_id: &str, issue_id: &str) -> Result<bool> {
31 let conn = self.inner.conn.lock().await;24 let conn = self.inner.conn.lock().await;
32 let tx = conn.unchecked_transaction().await.map_err(db_err)?;25 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -75,8 +68,6 @@ impl Store {
75 finish(tx, outcome).await68 finish(tx, outcome).await
76 }69 }
77 70
78- /// Unpins an issue. Returns `true` when it was pinned and `false` when it was not. Nothing
79- /// is checked beyond the pair of ids, so an unknown issue simply reads as not pinned.
80 pub async fn unpin_issue(&self, repo_id: &str, issue_id: &str) -> Result<bool> {71 pub async fn unpin_issue(&self, repo_id: &str, issue_id: &str) -> Result<bool> {
81 let conn = self.inner.conn.lock().await;72 let conn = self.inner.conn.lock().await;
82 let removed = conn73 let removed = conn
@@ -89,7 +80,6 @@ impl Store {
89 Ok(removed > 0)80 Ok(removed > 0)
90 }81 }
91 82
92- /// The pinned issues of a repo in pin order.
93 pub async fn pinned_issues(&self, repo_id: &str) -> Result<Vec<Issue>> {83 pub async fn pinned_issues(&self, repo_id: &str) -> Result<Vec<Issue>> {
94 let conn = self.read_conn().await;84 let conn = self.read_conn().await;
95 fetch_all(85 fetch_all(
@@ -104,7 +94,6 @@ impl Store {
104 .await94 .await
105 }95 }
106 96
107- /// Whether the issue is pinned in this repo.
108 pub async fn is_pinned(&self, repo_id: &str, issue_id: &str) -> Result<bool> {97 pub async fn is_pinned(&self, repo_id: &str, issue_id: &str) -> Result<bool> {
109 let conn = self.read_conn().await;98 let conn = self.read_conn().await;
110 is_pinned_on(&conn, repo_id, issue_id).await99 is_pinned_on(&conn, repo_id, issue_id).await
@@ -130,12 +119,10 @@ mod tests {
130 (store, tahinli, repo.id, dir)119 (store, tahinli, repo.id, dir)
131 }120 }
132 121
133- // One store, one scenario per repo so issue numbers and pin slots never mix.
134 #[tokio::test]122 #[tokio::test]
135 async fn pin_rules_hold_in_each_scenario() {123 async fn pin_rules_hold_in_each_scenario() {
136 let (store, tahinli, repo, _dir) = fixture().await;124 let (store, tahinli, repo, _dir) = fixture().await;
137 125
138- // Scenario 1: pins keep their order and a fourth pin is refused.
139 let mut ids = Vec::new();126 let mut ids = Vec::new();
140 for i in 0..4 {127 for i in 0..4 {
141 let issue = store128 let issue = store
@@ -174,7 +161,6 @@ mod tests {
174 .collect();161 .collect();
175 assert_eq!(pinned, vec![3, 1, 4], "order: listing");162 assert_eq!(pinned, vec![3, 1, 4], "order: listing");
176 163
177- // Scenario 2: pinning twice is idempotent and unpinning frees a slot.
178 let repo2 = store164 let repo2 = store
179 .create_repo(165 .create_repo(
180 &tahinli.id,166 &tahinli.id,
@@ -231,7 +217,6 @@ mod tests {
231 .collect();217 .collect();
232 assert_eq!(numbers, vec![1, 3, 4], "unpin: listing");218 assert_eq!(numbers, vec![1, 3, 4], "unpin: listing");
233 219
234- // Scenario 3: pull requests and issues of another repo cannot be pinned.
235 let repo3 = store220 let repo3 = store
236 .create_repo(&tahinli.id, "forge-foreign", "", Visibility::Public, "main")221 .create_repo(&tahinli.id, "forge-foreign", "", Visibility::Public, "main")
237 .await222 .await
crates/forge-core/src/store/profile_pins.rsmodified+0 -19
@@ -1,18 +1,12 @@
1-//! Profile pins: up to `MAX_PROFILE_PINS` repos of a user or organization shown first on its
2-//! profile. The stored shape is in migrations/0037_profile_pins.sql. Visibility is not checked
3-//! here; the profile page filters by what the viewer may read.
4-
5 use std::collections::HashSet;1 use std::collections::HashSet;
6 2
7 use super::{REPO_COLS, Store, col_text, db_err, fetch_all, fetch_opt, finish, map_repo};3 use super::{REPO_COLS, Store, col_text, db_err, fetch_all, fetch_opt, finish, map_repo};
8 use crate::error::{Error, Result};4 use crate::error::{Error, Result};
9 use crate::model::Repo;5 use crate::model::Repo;
10 6
11-/// Most repos one profile may pin.
12 pub const MAX_PROFILE_PINS: usize = 6;7 pub const MAX_PROFILE_PINS: usize = 6;
13 8
14 impl Store {9 impl Store {
15- /// The repos pinned on a profile, in pin order. Not filtered by visibility.
16 pub async fn profile_pins(&self, user_id: &str) -> Result<Vec<Repo>> {10 pub async fn profile_pins(&self, user_id: &str) -> Result<Vec<Repo>> {
17 let conn = self.read_conn().await;11 let conn = self.read_conn().await;
18 fetch_all(12 fetch_all(
@@ -27,8 +21,6 @@ impl Store {
27 .await21 .await
28 }22 }
29 23
30- /// Every repo the owner owns, most recently active first (the latest push, or the creation
31- /// time when it never pushed). Not filtered by visibility.
32 pub async fn owner_repos_by_activity(&self, owner_id: &str) -> Result<Vec<Repo>> {24 pub async fn owner_repos_by_activity(&self, owner_id: &str) -> Result<Vec<Repo>> {
33 let conn = self.read_conn().await;25 let conn = self.read_conn().await;
34 fetch_all(26 fetch_all(
@@ -45,10 +37,6 @@ impl Store {
45 .await37 .await
46 }38 }
47 39
48- /// Replaces the pins of `user_id` with `repo_ids`, kept in the order given. Every repo must be
49- /// owned by that user (for an organization, by the org). More than `MAX_PROFILE_PINS` repos,
50- /// a repo listed twice, or a repo the owner does not own is `Invalid`, and then nothing
51- /// changes. The replacement is one transaction.
52 pub async fn set_profile_pins(&self, user_id: &str, repo_ids: &[String]) -> Result<()> {40 pub async fn set_profile_pins(&self, user_id: &str, repo_ids: &[String]) -> Result<()> {
53 if repo_ids.len() > MAX_PROFILE_PINS {41 if repo_ids.len() > MAX_PROFILE_PINS {
54 return Err(Error::Invalid(format!(42 return Err(Error::Invalid(format!(
@@ -146,13 +134,10 @@ mod tests {
146 .collect()134 .collect()
147 }135 }
148 136
149- // One store serves every scenario. Each scenario gets its own owner, so
150- // pin sets and the "repo-N" names never collide.
151 #[tokio::test]137 #[tokio::test]
152 async fn profile_pin_rules() {138 async fn profile_pin_rules() {
153 let (store, tahinli, foreign, _dir) = fixture().await;139 let (store, tahinli, foreign, _dir) = fixture().await;
154 140
155- // Pins keep the order given and each save replaces the old set.
156 let ids = make_repos(&store, &tahinli, 3).await;141 let ids = make_repos(&store, &tahinli, 3).await;
157 store142 store
158 .set_profile_pins(&tahinli, &[ids[2].clone(), ids[0].clone()])143 .set_profile_pins(&tahinli, &[ids[2].clone(), ids[0].clone()])
@@ -178,7 +163,6 @@ mod tests {
178 "empty clears the pins"163 "empty clears the pins"
179 );164 );
180 165
181- // More than six pins is refused and the old pins stay.
182 let big = store.create_user("big", None, "h", false).await.unwrap();166 let big = store.create_user("big", None, "h", false).await.unwrap();
183 let ids = make_repos(&store, &big.id, 7).await;167 let ids = make_repos(&store, &big.id, 7).await;
184 store.set_profile_pins(&big.id, &ids[..2]).await.unwrap();168 store.set_profile_pins(&big.id, &ids[..2]).await.unwrap();
@@ -193,7 +177,6 @@ mod tests {
193 "old pins kept"177 "old pins kept"
194 );178 );
195 179
196- // Foreign and repeated repos are refused atomically.
197 let strict = store.create_user("strict", None, "h", false).await.unwrap();180 let strict = store.create_user("strict", None, "h", false).await.unwrap();
198 let ids = make_repos(&store, &strict.id, 1).await;181 let ids = make_repos(&store, &strict.id, 1).await;
199 store.set_profile_pins(&strict.id, &ids[..1]).await.unwrap();182 store.set_profile_pins(&strict.id, &ids[..1]).await.unwrap();
@@ -217,7 +200,6 @@ mod tests {
217 "nothing changed"200 "nothing changed"
218 );201 );
219 202
220- // Deleting a pinned repo removes its pin.
221 let gone = store.create_user("gone", None, "h", false).await.unwrap();203 let gone = store.create_user("gone", None, "h", false).await.unwrap();
222 let ids = make_repos(&store, &gone.id, 2).await;204 let ids = make_repos(&store, &gone.id, 2).await;
223 store.set_profile_pins(&gone.id, &ids).await.unwrap();205 store.set_profile_pins(&gone.id, &ids).await.unwrap();
@@ -228,7 +210,6 @@ mod tests {
228 "deleted pin removed"210 "deleted pin removed"
229 );211 );
230 212
231- // The activity list holds every owned repo and no foreign one.
232 let active = store.create_user("active", None, "h", false).await.unwrap();213 let active = store.create_user("active", None, "h", false).await.unwrap();
233 make_repos(&store, &active.id, 2).await;214 make_repos(&store, &active.id, 2).await;
234 let listed = store.owner_repos_by_activity(&active.id).await.unwrap();215 let listed = store.owner_repos_by_activity(&active.id).await.unwrap();
crates/forge-core/src/store/pull_viewed.rsmodified+0 -8
@@ -1,8 +1,3 @@
1-//! Files a reviewer marked Viewed on a pull request's Files tab (migration 0070). One row per user,
2-//! pull request and path, holding the blob id the mark was made for. The web layer compares that
3-//! blob with the file's current one; this store only keeps the rows. Rows go with the user and
4-//! with the pull request's issue (ON DELETE CASCADE).
5-
6 use std::collections::HashMap;1 use std::collections::HashMap;
7 2
8 use super::{Store, col_text, db_err, fetch_all};3 use super::{Store, col_text, db_err, fetch_all};
@@ -10,7 +5,6 @@ use crate::error::Result;
10 use crate::time::now_stamp;5 use crate::time::now_stamp;
11 6
12 impl Store {7 impl Store {
13- /// The viewer's marks on one pull request as `path -> blob`.
14 pub async fn pull_viewed_files(8 pub async fn pull_viewed_files(
15 &self,9 &self,
16 user_id: &str,10 user_id: &str,
@@ -27,7 +21,6 @@ impl Store {
27 Ok(rows.into_iter().collect())21 Ok(rows.into_iter().collect())
28 }22 }
29 23
30- /// Marks `path` viewed at `blob`, replacing an earlier mark of the same path.
31 pub async fn set_pull_file_viewed(24 pub async fn set_pull_file_viewed(
32 &self,25 &self,
33 user_id: &str,26 user_id: &str,
@@ -54,7 +47,6 @@ impl Store {
54 Ok(())47 Ok(())
55 }48 }
56 49
57- /// Removes the viewer's mark on `path`. A path that was never marked is not an error.
58 pub async fn clear_pull_file_viewed(50 pub async fn clear_pull_file_viewed(
59 &self,51 &self,
60 user_id: &str,52 user_id: &str,
crates/forge-core/src/store/pulls_list_extra.rsmodified+0 -5
@@ -1,5 +1,3 @@
1-//! Extra pull request queries for the pull request list page.
2-
3 use std::collections::HashSet;1 use std::collections::HashSet;
4 2
5 use turso::Value;3 use turso::Value;
@@ -8,14 +6,11 @@ use super::{Store, col_int, fetch_all};
8 use crate::error::Result;6 use crate::error::Result;
9 7
10 impl Store {8 impl Store {
11- /// Which of `numbers` are draft pull requests of this repo.
12 pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {9 pub async fn draft_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {
13 self.pull_numbers_where(repo_id, numbers, "p.draft = 1")10 self.pull_numbers_where(repo_id, numbers, "p.draft = 1")
14 .await11 .await
15 }12 }
16 13
17- /// Which of `numbers` are merged pull requests of this repo. Numbers that are issues, open
18- /// or closed without a merge are left out.
19 pub async fn merged_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {14 pub async fn merged_numbers(&self, repo_id: &str, numbers: &[i64]) -> Result<HashSet<i64>> {
20 self.pull_numbers_where(repo_id, numbers, "p.merged_at IS NOT NULL")15 self.pull_numbers_where(repo_id, numbers, "p.merged_at IS NOT NULL")
21 .await16 .await
crates/forge-core/src/store/push_recent.rsmodified+0 -17
@@ -1,21 +1,14 @@
1-//! Recent branch pushes by one user, for the repo home banner.
2-
3 use turso::Value;1 use turso::Value;
4 2
5 use super::{Store, col_text, db_err, fetch_all, new_id};3 use super::{Store, col_text, db_err, fetch_all, new_id};
6 use crate::error::Result;4 use crate::error::Result;
7 use crate::model::Id;5 use crate::model::Id;
8 6
9-/// The all-zero object ids that mark a ref deletion: SHA-1 (40 digits) and SHA-256 (64 digits).
10 pub(super) const ZERO_OID_SHA1: &str = "0000000000000000000000000000000000000000";7 pub(super) const ZERO_OID_SHA1: &str = "0000000000000000000000000000000000000000";
11 pub(super) const ZERO_OID_SHA256: &str =8 pub(super) const ZERO_OID_SHA256: &str =
12 "0000000000000000000000000000000000000000000000000000000000000000";9 "0000000000000000000000000000000000000000000000000000000000000000";
13 10
14 impl Store {11 impl Store {
15- /// Branches `pusher_id` pushed to in any of `repo_ids` at or after `since` (an RFC 3339
16- /// stamp). Returns `(repo_id, branch, at)` with one row per repo and branch, `at` being the
17- /// latest push time, newest first. Ref deletions are left out, and so are refs outside
18- /// `refs/heads/`.
19 pub async fn recent_branch_pushes(12 pub async fn recent_branch_pushes(
20 &self,13 &self,
21 repo_ids: &[&str],14 repo_ids: &[&str],
@@ -25,7 +18,6 @@ impl Store {
25 if repo_ids.is_empty() {18 if repo_ids.is_empty() {
26 return Ok(Vec::new());19 return Ok(Vec::new());
27 }20 }
28- // Parameters: ?1 pusher, ?2 since, ?3 and ?4 zero oids, ?5.. repo ids.
29 let placeholders: Vec<String> = (5..5 + repo_ids.len()).map(|i| format!("?{i}")).collect();21 let placeholders: Vec<String> = (5..5 + repo_ids.len()).map(|i| format!("?{i}")).collect();
30 let sql = format!(22 let sql = format!(
31 "SELECT repo_id, ref_name, MAX(created_at) FROM push_events \23 "SELECT repo_id, ref_name, MAX(created_at) FROM push_events \
@@ -55,8 +47,6 @@ impl Store {
55 .collect())47 .collect())
56 }48 }
57 49
58- /// Records a push event with an explicit time instead of now. The recent-pushes query reads
59- /// `created_at`, so tests use this to place an event in the past.
60 pub async fn record_push_event_at(50 pub async fn record_push_event_at(
61 &self,51 &self,
62 repo_id: &str,52 repo_id: &str,
@@ -116,8 +106,6 @@ mod tests {
116 (dir, store, tahinli.id, bob.id, demo.id, other.id)106 (dir, store, tahinli.id, bob.id, demo.id, other.id)
117 }107 }
118 108
119- // One store serves both checks. The first one needs the store to hold only
120- // its own pushes, so the "now" push of the second one runs after it.
121 #[tokio::test]109 #[tokio::test]
122 async fn recent_branch_pushes_rules_and_empty_inputs() {110 async fn recent_branch_pushes_rules_and_empty_inputs() {
123 let (_dir, store, tahinli, bob, demo, other) = store_with_repos().await;111 let (_dir, store, tahinli, bob, demo, other) = store_with_repos().await;
@@ -133,17 +121,14 @@ mod tests {
133 .record_push_event_at(&demo, &tahinli, "refs/heads/feature", OID, OID, &newer)121 .record_push_event_at(&demo, &tahinli, "refs/heads/feature", OID, OID, &newer)
134 .await122 .await
135 .unwrap();123 .unwrap();
136- // A deletion is not a recent push.
137 store124 store
138 .record_push_event_at(&demo, &tahinli, "refs/heads/gone", OID, ZERO, &newer)125 .record_push_event_at(&demo, &tahinli, "refs/heads/gone", OID, ZERO, &newer)
139 .await126 .await
140 .unwrap();127 .unwrap();
141- // Tags are not branches.
142 store128 store
143 .record_push_event_at(&demo, &tahinli, "refs/tags/v1", ZERO, OID, &newer)129 .record_push_event_at(&demo, &tahinli, "refs/tags/v1", ZERO, OID, &newer)
144 .await130 .await
145 .unwrap();131 .unwrap();
146- // Another user's push, and an old one, are left out.
147 store132 store
148 .record_push_event_at(&demo, &bob, "refs/heads/bobs", ZERO, OID, &newer)133 .record_push_event_at(&demo, &bob, "refs/heads/bobs", ZERO, OID, &newer)
149 .await134 .await
@@ -159,7 +144,6 @@ mod tests {
159 )144 )
160 .await145 .await
161 .unwrap();146 .unwrap();
162- // Outside the repo ids asked for.
163 store147 store
164 .record_push_event_at(&other, &tahinli, "refs/heads/elsewhere", ZERO, OID, &newer)148 .record_push_event_at(&other, &tahinli, "refs/heads/elsewhere", ZERO, OID, &newer)
165 .await149 .await
@@ -175,7 +159,6 @@ mod tests {
175 "only the newest recent branch push"159 "only the newest recent branch push"
176 );160 );
177 161
178- // No repo ids, or a `since` in the future, gives nothing.
179 store162 store
180 .record_push_event(&demo, &tahinli, "refs/heads/feature", ZERO, OID, "test")163 .record_push_event(&demo, &tahinli, "refs/heads/feature", ZERO, OID, "test")
181 .await164 .await
crates/forge-core/src/store/reactions.rsmodified+0 -17
@@ -1,7 +1,3 @@
1-//! Emoji reactions on issues, pull requests and comments. One row per user, target and emoji:
2-//! toggling adds the row or removes it. Deleting a target removes its reactions in the issue and
3-//! comment delete paths (`store/issues.rs`), and deleting a user removes theirs (`user_delete.rs`).
4-
5 use std::collections::{BTreeMap, HashMap};1 use std::collections::{BTreeMap, HashMap};
6 2
7 use super::{3 use super::{
@@ -12,8 +8,6 @@ use crate::reactions::{Reaction, ReactionMap, ReactionSummary, ReactionTarget, S
12 use crate::time::now_stamp;8 use crate::time::now_stamp;
13 9
14 impl Store {10 impl Store {
15- /// Adds the reaction when the user has not put it on the target yet, removes it when they have.
16- /// Returns whether it is on afterwards. A target that does not exist is `NotFound`.
17 pub async fn toggle_reaction(11 pub async fn toggle_reaction(
18 &self,12 &self,
19 kind: ReactionTarget,13 kind: ReactionTarget,
@@ -75,9 +69,6 @@ impl Store {
75 finish(tx, outcome).await69 finish(tx, outcome).await
76 }70 }
77 71
78- /// The reactions of every target in `ids` in one batched query (chunked only past 500 ids).
79- /// Targets without reactions have no entry. Each entry lists the reactions in display order,
80- /// with the count, whether `viewer` made it, and the first ten usernames.
81 pub async fn reactions_for(72 pub async fn reactions_for(
82 &self,73 &self,
83 kind: ReactionTarget,74 kind: ReactionTarget,
@@ -88,7 +79,6 @@ impl Store {
88 if ids.is_empty() {79 if ids.is_empty() {
89 return Ok(out);80 return Ok(out);
90 }81 }
91- // target id -> reaction -> (user id, username) in reaction order.
92 let mut grouped: HashMap<String, BTreeMap<Reaction, Vec<(String, String)>>> =82 let mut grouped: HashMap<String, BTreeMap<Reaction, Vec<(String, String)>>> =
93 HashMap::new();83 HashMap::new();
94 let conn = self.read_conn().await;84 let conn = self.read_conn().await;
@@ -182,13 +172,10 @@ mod tests {
182 }172 }
183 }173 }
184 174
185- // One store serves every scenario. Each scenario opens its own issue, so
186- // the reactions never overlap.
187 #[tokio::test]175 #[tokio::test]
188 async fn reaction_scenarios_share_one_store() {176 async fn reaction_scenarios_share_one_store() {
189 let fx = fixture().await;177 let fx = fixture().await;
190 178
191- // Toggle adds then removes, and a missing target is refused.
192 let issue = fx179 let issue = fx
193 .store180 .store
194 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")181 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")
@@ -237,7 +224,6 @@ mod tests {
237 "toggle: missing target is NotFound"224 "toggle: missing target is NotFound"
238 );225 );
239 226
240- // Aggregates count users and flag the viewer's own reactions.
241 let issue = fx227 let issue = fx
242 .store228 .store
243 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")229 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")
@@ -268,7 +254,6 @@ mod tests {
268 )254 )
269 .await255 .await
270 .unwrap();256 .unwrap();
271- // A comment reaction is not an issue reaction, even with the same id space.
272 fx.store257 fx.store
273 .toggle_reaction(258 .toggle_reaction(
274 ReactionTarget::Comment,259 ReactionTarget::Comment,
@@ -327,7 +312,6 @@ mod tests {
327 "comment viewer flag"312 "comment viewer flag"
328 );313 );
329 314
330- // Summaries keep the first ten names and the full count.
331 let issue = fx315 let issue = fx
332 .store316 .store
333 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")317 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")
@@ -354,7 +338,6 @@ mod tests {
354 assert_eq!(summary.users.len(), SUMMARY_USERS, "summary: capped names");338 assert_eq!(summary.users.len(), SUMMARY_USERS, "summary: capped names");
355 assert_eq!(summary.users[0], "user0", "summary: first name");339 assert_eq!(summary.users[0], "user0", "summary: first name");
356 340
357- // Deleting a comment removes its reactions.
358 let issue = fx341 let issue = fx
359 .store342 .store
360 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")343 .create_issue(&fx.repo_id, &fx.tahinli.id, "t", "")
crates/forge-core/src/store/releases.rsmodified+0 -39
@@ -1,6 +1,3 @@
1-//! Release storage: releases, their assets and the download counter. Blob bytes are not here;
2-//! the web layer writes and deletes them, using the ids this module returns.
3-
4 use turso::transaction::Transaction;1 use turso::transaction::Transaction;
5 use turso::{Row, Value};2 use turso::{Row, Value};
6 3
@@ -12,14 +9,12 @@ use crate::error::{Error, Result};
12 use crate::releases::{NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit};9 use crate::releases::{NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit};
13 use crate::time::now_stamp;10 use crate::time::now_stamp;
14 11
15-/// Release columns, with the author's name joined in. Use with the `r` and `u` aliases.
16 const RELEASE_COLS: &str = "r.id, r.repo_id, r.tag, r.target_oid, r.title, r.body, r.draft, \12 const RELEASE_COLS: &str = "r.id, r.repo_id, r.tag, r.target_oid, r.title, r.body, r.draft, \
17 r.prerelease, r.author_id, u.username, r.created_at, r.published_at";13 r.prerelease, r.author_id, u.username, r.created_at, r.published_at";
18 14
19 const ASSET_COLS: &str = "id, release_id, name, size, sha256, content_type, download_count, \15 const ASSET_COLS: &str = "id, release_id, name, size, sha256, content_type, download_count, \
20 uploader_id, created_at";16 uploader_id, created_at";
21 17
22-/// Newest first: by publish time, drafts by creation time.
23 const RELEASE_ORDER: &str = "COALESCE(r.published_at, r.created_at) DESC, r.id DESC";18 const RELEASE_ORDER: &str = "COALESCE(r.published_at, r.created_at) DESC, r.id DESC";
24 19
25 fn map_release(row: &Row) -> Result<Release> {20 fn map_release(row: &Row) -> Result<Release> {
@@ -60,7 +55,6 @@ fn release_sql(filter: &str) -> String {
60 format!("SELECT {RELEASE_COLS} FROM releases r JOIN users u ON u.id = r.author_id {filter}")55 format!("SELECT {RELEASE_COLS} FROM releases r JOIN users u ON u.id = r.author_id {filter}")
61 }56 }
62 57
63-/// Removes the releases of a repo and their assets rows. Called inside `Store::delete_repo`.
64 pub(super) async fn delete_repo_release_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {58 pub(super) async fn delete_repo_release_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {
65 let id = repo_id.to_string();59 let id = repo_id.to_string();
66 tx.execute(60 tx.execute(
@@ -76,8 +70,6 @@ pub(super) async fn delete_repo_release_rows(tx: &Transaction<'_>, repo_id: &str
76 }70 }
77 71
78 impl Store {72 impl Store {
79- /// Creates a release. A second release for the same tag is `Conflict`. A draft has no
80- /// `published_at`; any other release is published now.
81 pub async fn create_release(&self, new: &NewRelease<'_>) -> Result<Release> {73 pub async fn create_release(&self, new: &NewRelease<'_>) -> Result<Release> {
82 let id = new_id();74 let id = new_id();
83 let now = now_stamp();75 let now = now_stamp();
@@ -107,7 +99,6 @@ impl Store {
107 self.release(&id).await?.ok_or(Error::NotFound)99 self.release(&id).await?.ok_or(Error::NotFound)
108 }100 }
109 101
110- /// One release by id.
111 pub async fn release(&self, id: &str) -> Result<Option<Release>> {102 pub async fn release(&self, id: &str) -> Result<Option<Release>> {
112 let conn = self.read_conn().await;103 let conn = self.read_conn().await;
113 fetch_opt(104 fetch_opt(
@@ -119,7 +110,6 @@ impl Store {
119 .await110 .await
120 }111 }
121 112
122- /// The release for a tag in a repo, if any.
123 pub async fn release_by_tag(&self, repo_id: &str, tag: &str) -> Result<Option<Release>> {113 pub async fn release_by_tag(&self, repo_id: &str, tag: &str) -> Result<Option<Release>> {
124 let conn = self.read_conn().await;114 let conn = self.read_conn().await;
125 fetch_opt(115 fetch_opt(
@@ -131,8 +121,6 @@ impl Store {
131 .await121 .await
132 }122 }
133 123
134- /// Every release of a repo, drafts included, newest first. The caller hides drafts from
135- /// viewers without Write.
136 pub async fn list_releases(&self, repo_id: &str) -> Result<Vec<Release>> {124 pub async fn list_releases(&self, repo_id: &str) -> Result<Vec<Release>> {
137 let conn = self.read_conn().await;125 let conn = self.read_conn().await;
138 fetch_all(126 fetch_all(
@@ -144,7 +132,6 @@ impl Store {
144 .await132 .await
145 }133 }
146 134
147- /// The newest published release that is neither a draft nor a pre-release.
148 pub async fn latest_release(&self, repo_id: &str) -> Result<Option<Release>> {135 pub async fn latest_release(&self, repo_id: &str) -> Result<Option<Release>> {
149 let conn = self.read_conn().await;136 let conn = self.read_conn().await;
150 fetch_opt(137 fetch_opt(
@@ -159,8 +146,6 @@ impl Store {
159 .await146 .await
160 }147 }
161 148
162- /// Updates the editable fields. A release that stops being a draft gets its `published_at`
163- /// now, once. Returns false when the release is gone.
164 pub async fn update_release(&self, id: &str, edit: &ReleaseEdit<'_>) -> Result<bool> {149 pub async fn update_release(&self, id: &str, edit: &ReleaseEdit<'_>) -> Result<bool> {
165 let conn = self.inner.conn.lock().await;150 let conn = self.inner.conn.lock().await;
166 let changed = conn151 let changed = conn
@@ -182,9 +167,6 @@ impl Store {
182 Ok(changed == 1)167 Ok(changed == 1)
183 }168 }
184 169
185- /// Deletes a release and its asset rows, keeping the git tag. Returns the ids of the assets
186- /// that were removed, so the caller can delete their blobs, or `None` if there is no such
187- /// release.
188 pub async fn delete_release(&self, id: &str) -> Result<Option<Vec<String>>> {170 pub async fn delete_release(&self, id: &str) -> Result<Option<Vec<String>>> {
189 let conn = self.inner.conn.lock().await;171 let conn = self.inner.conn.lock().await;
190 let tx = conn.unchecked_transaction().await.map_err(db_err)?;172 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -213,7 +195,6 @@ impl Store {
213 finish(tx, outcome).await195 finish(tx, outcome).await
214 }196 }
215 197
216- /// The asset with this name on a release.
217 pub async fn release_asset(198 pub async fn release_asset(
218 &self,199 &self,
219 release_id: &str,200 release_id: &str,
@@ -229,7 +210,6 @@ impl Store {
229 .await210 .await
230 }211 }
231 212
232- /// One asset by id.
233 pub async fn release_asset_by_id(&self, id: &str) -> Result<Option<ReleaseAsset>> {213 pub async fn release_asset_by_id(&self, id: &str) -> Result<Option<ReleaseAsset>> {
234 let conn = self.read_conn().await;214 let conn = self.read_conn().await;
235 fetch_opt(215 fetch_opt(
@@ -241,7 +221,6 @@ impl Store {
241 .await221 .await
242 }222 }
243 223
244- /// The assets of a release, by name.
245 pub async fn list_release_assets(&self, release_id: &str) -> Result<Vec<ReleaseAsset>> {224 pub async fn list_release_assets(&self, release_id: &str) -> Result<Vec<ReleaseAsset>> {
246 let conn = self.read_conn().await;225 let conn = self.read_conn().await;
247 fetch_all(226 fetch_all(
@@ -253,7 +232,6 @@ impl Store {
253 .await232 .await
254 }233 }
255 234
256- /// Adds an asset row. A second asset with the same name on the release is `Conflict`.
257 pub async fn add_asset(&self, new: &NewAsset<'_>) -> Result<ReleaseAsset> {235 pub async fn add_asset(&self, new: &NewAsset<'_>) -> Result<ReleaseAsset> {
258 let size = i64::try_from(new.size).map_err(|_| Error::Invalid("asset too large".into()))?;236 let size = i64::try_from(new.size).map_err(|_| Error::Invalid("asset too large".into()))?;
259 let now = now_stamp();237 let now = now_stamp();
@@ -281,10 +259,6 @@ impl Store {
281 .ok_or_else(missing_row)259 .ok_or_else(missing_row)
282 }260 }
283 261
284- /// Swaps the file of an existing asset in one statement. The row takes the new asset's id,
285- /// size, digest, content type, uploader and time, and keeps its release, name and download
286- /// count. The new blob must already be written under `assets/<new.id>`; the caller deletes the
287- /// old blob after this returns. `NotFound` when `old_id` is gone.
288 pub async fn replace_asset(&self, old_id: &str, new: &NewAsset<'_>) -> Result<ReleaseAsset> {262 pub async fn replace_asset(&self, old_id: &str, new: &NewAsset<'_>) -> Result<ReleaseAsset> {
289 let size = i64::try_from(new.size).map_err(|_| Error::Invalid("asset too large".into()))?;263 let size = i64::try_from(new.size).map_err(|_| Error::Invalid("asset too large".into()))?;
290 let changed = {264 let changed = {
@@ -313,8 +287,6 @@ impl Store {
313 .ok_or_else(missing_row)287 .ok_or_else(missing_row)
314 }288 }
315 289
316- /// Points a release at another tag and commit. A tag another release already uses is
317- /// `Conflict`. Returns false when the release is gone.
318 pub async fn set_release_tag(&self, id: &str, tag: &str, target_oid: &str) -> Result<bool> {290 pub async fn set_release_tag(&self, id: &str, tag: &str, target_oid: &str) -> Result<bool> {
319 let conn = self.inner.conn.lock().await;291 let conn = self.inner.conn.lock().await;
320 let changed = conn292 let changed = conn
@@ -327,7 +299,6 @@ impl Store {
327 Ok(changed == 1)299 Ok(changed == 1)
328 }300 }
329 301
330- /// Deletes one asset row. Returns false when it is already gone.
331 pub async fn delete_release_asset(&self, id: &str) -> Result<bool> {302 pub async fn delete_release_asset(&self, id: &str) -> Result<bool> {
332 let conn = self.inner.conn.lock().await;303 let conn = self.inner.conn.lock().await;
333 let removed = conn304 let removed = conn
@@ -340,7 +311,6 @@ impl Store {
340 Ok(removed == 1)311 Ok(removed == 1)
341 }312 }
342 313
343- /// Adds one to an asset's download counter.
344 pub async fn count_asset_download(&self, id: &str) -> Result<()> {314 pub async fn count_asset_download(&self, id: &str) -> Result<()> {
345 let conn = self.inner.conn.lock().await;315 let conn = self.inner.conn.lock().await;
346 conn.execute(316 conn.execute(
@@ -352,8 +322,6 @@ impl Store {
352 Ok(())322 Ok(())
353 }323 }
354 324
355- /// Every asset id of a repo's releases. Read before `delete_repo`, which removes the rows,
356- /// so the web layer can delete the blobs.
357 pub async fn repo_release_asset_ids(&self, repo_id: &str) -> Result<Vec<String>> {325 pub async fn repo_release_asset_ids(&self, repo_id: &str) -> Result<Vec<String>> {
358 let conn = self.read_conn().await;326 let conn = self.read_conn().await;
359 fetch_all(327 fetch_all(
@@ -406,13 +374,10 @@ mod tests {
406 .id374 .id
407 }375 }
408 376
409- // Every scenario gets its own repo in one shared store, so the per-repo
410- // assertions cannot see another scenario's releases or assets.
411 #[tokio::test]377 #[tokio::test]
412 async fn release_lifecycle_per_repo() {378 async fn release_lifecycle_per_repo() {
413 let (_dir, store, user, _repo) = store_with_repo().await;379 let (_dir, store, user, _repo) = store_with_repo().await;
414 380
415- // Drafts stay unpublished, and tags are unique per repo.
416 let repo = add_repo(&store, &user, "drafts").await;381 let repo = add_repo(&store, &user, "drafts").await;
417 let draft = store382 let draft = store
418 .create_release(&new_release(&repo, &user, "v1", true))383 .create_release(&new_release(&repo, &user, "v1", true))
@@ -434,7 +399,6 @@ mod tests {
434 "duplicate tag: {again:?}"399 "duplicate tag: {again:?}"
435 );400 );
436 401
437- // Publishing sets published_at once; a prerelease is not "latest".
438 let repo = add_repo(&store, &user, "publish").await;402 let repo = add_repo(&store, &user, "publish").await;
439 let rel = store403 let rel = store
440 .create_release(&new_release(&repo, &user, "v1", true))404 .create_release(&new_release(&repo, &user, "v1", true))
@@ -479,7 +443,6 @@ mod tests {
479 "latest skips the prerelease"443 "latest skips the prerelease"
480 );444 );
481 445
482- // Downloads are counted; deleting a release returns its blob ids.
483 let repo = add_repo(&store, &user, "assets").await;446 let repo = add_repo(&store, &user, "assets").await;
484 let rel = store447 let rel = store
485 .create_release(&new_release(&repo, &user, "v1", false))448 .create_release(&new_release(&repo, &user, "v1", false))
@@ -523,7 +486,6 @@ mod tests {
523 "second delete"486 "second delete"
524 );487 );
525 488
526- // Replacing an asset swaps its file but keeps its name and counter.
527 let repo = add_repo(&store, &user, "replace").await;489 let repo = add_repo(&store, &user, "replace").await;
528 let rel = store490 let rel = store
529 .create_release(&new_release(&repo, &user, "v1", false))491 .create_release(&new_release(&repo, &user, "v1", false))
@@ -591,7 +553,6 @@ mod tests {
591 "replacing a missing asset: {gone:?}"553 "replacing a missing asset: {gone:?}"
592 );554 );
593 555
594- // Retagging moves the release, but not onto a tag another release uses.
595 let repo = add_repo(&store, &user, "retag").await;556 let repo = add_repo(&store, &user, "retag").await;
596 let first = store557 let first = store
597 .create_release(&new_release(&repo, &user, "v1", true))558 .create_release(&new_release(&repo, &user, "v1", true))
crates/forge-core/src/store/replication.rsmodified+0 -14
@@ -1,21 +1,15 @@
1-//! Standby replication status: one row per replicated subject (`db` or a repo id), shown on
2-//! `/admin/replication`. The replication worker writes it; nothing else does.
3-
4 use turso::{Row, Value};1 use turso::{Row, Value};
5 2
6 use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt};3 use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt};
7 use crate::error::Result;4 use crate::error::Result;
8 use crate::time::now_stamp;5 use crate::time::now_stamp;
9 6
10-/// The subject name used for the database snapshot row.
11 pub const DB_SUBJECT: &str = "db";7 pub const DB_SUBJECT: &str = "db";
12 8
13 const STATUS_COLS: &str = "subject, last_ok_at, last_error, last_attempt_at, refs_sha256";9 const STATUS_COLS: &str = "subject, last_ok_at, last_error, last_attempt_at, refs_sha256";
14 10
15-/// One row of `replication_status`.
16 #[derive(Debug, Clone, PartialEq, Eq)]11 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct ReplicationStatus {12 pub struct ReplicationStatus {
18- /// `db` or a repo id.
19 pub subject: String,13 pub subject: String,
20 pub last_ok_at: Option<String>,14 pub last_ok_at: Option<String>,
21 pub last_error: Option<String>,15 pub last_error: Option<String>,
@@ -38,8 +32,6 @@ fn opt(v: Option<&str>) -> Value {
38 }32 }
39 33
40 impl Store {34 impl Store {
41- /// Records a successful attempt for `subject`: sets `last_ok_at` and `last_attempt_at`,
42- /// clears `last_error`, and stores `refs_sha256` when given (repo pushes pass it).
43 pub async fn record_replication_ok(35 pub async fn record_replication_ok(
44 &self,36 &self,
45 subject: &str,37 subject: &str,
@@ -64,7 +56,6 @@ impl Store {
64 Ok(())56 Ok(())
65 }57 }
66 58
67- /// Records a failed attempt for `subject`. `last_ok_at` and `refs_sha256` are kept.
68 pub async fn record_replication_error(&self, subject: &str, error: &str) -> Result<()> {59 pub async fn record_replication_error(&self, subject: &str, error: &str) -> Result<()> {
69 let now = now_stamp();60 let now = now_stamp();
70 let conn = self.inner.conn.lock().await;61 let conn = self.inner.conn.lock().await;
@@ -84,21 +75,18 @@ impl Store {
84 Ok(())75 Ok(())
85 }76 }
86 77
87- /// The status row of `subject`, if it has ever been attempted.
88 pub async fn replication_status(&self, subject: &str) -> Result<Option<ReplicationStatus>> {78 pub async fn replication_status(&self, subject: &str) -> Result<Option<ReplicationStatus>> {
89 let sql = format!("SELECT {STATUS_COLS} FROM replication_status WHERE subject = ?1");79 let sql = format!("SELECT {STATUS_COLS} FROM replication_status WHERE subject = ?1");
90 let conn = self.read_conn().await;80 let conn = self.read_conn().await;
91 fetch_opt(&conn, &sql, (subject.to_owned(),), map_status).await81 fetch_opt(&conn, &sql, (subject.to_owned(),), map_status).await
92 }82 }
93 83
94- /// Every status row, ordered by subject (`db` sorts among the repo ids like any other).
95 pub async fn list_replication_status(&self) -> Result<Vec<ReplicationStatus>> {84 pub async fn list_replication_status(&self) -> Result<Vec<ReplicationStatus>> {
96 let sql = format!("SELECT {STATUS_COLS} FROM replication_status ORDER BY subject");85 let sql = format!("SELECT {STATUS_COLS} FROM replication_status ORDER BY subject");
97 let conn = self.read_conn().await;86 let conn = self.read_conn().await;
98 fetch_all(&conn, &sql, (), map_status).await87 fetch_all(&conn, &sql, (), map_status).await
99 }88 }
100 89
101- /// Removes the status row of `subject`. Used once a deleted repo is gone from the standby.
102 pub async fn delete_replication_status(&self, subject: &str) -> Result<()> {90 pub async fn delete_replication_status(&self, subject: &str) -> Result<()> {
103 let conn = self.inner.conn.lock().await;91 let conn = self.inner.conn.lock().await;
104 conn.execute(92 conn.execute(
@@ -123,8 +111,6 @@ mod tests {
123 (dir, store)111 (dir, store)
124 }112 }
125 113
126- // One store serves both checks. The list check runs first, so its exact
127- // subject list is not affected by the "r1" row used further down.
128 #[tokio::test]114 #[tokio::test]
129 async fn status_list_delete_and_ok_or_error_keep_other_fields() {115 async fn status_list_delete_and_ok_or_error_keep_other_fields() {
130 let (_dir, store) = store().await;116 let (_dir, store) = store().await;
crates/forge-core/src/store/repo_listing.rsmodified+0 -39
@@ -1,7 +1,3 @@
1-//! Paged repo listings filtered in SQL: the public listing (`/explore`) and the profile tabs (a
2-//! user's repos, a user's stars). Read access is decided in the query with the same rules as
3-//! `authz::authorize` for `Action::Read`, so no per-repo role lookup is needed.
4-
5 use turso::{Connection, Value};1 use turso::{Connection, Value};
6 2
7 use super::{3 use super::{
@@ -11,27 +7,16 @@ use super::{
11 use crate::error::Result;7 use crate::error::Result;
12 use crate::model::{Repo, User};8 use crate::model::{Repo, User};
13 9
14-/// Whose repos a profile tab lists.
15 #[derive(Debug, Clone, Copy, PartialEq, Eq)]10 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16 pub enum RepoScope<'a> {11 pub enum RepoScope<'a> {
17- /// The repos owned by this user or organization id.
18 OwnedBy(&'a str),12 OwnedBy(&'a str),
19- /// The repos this user id has starred.
20 StarredBy(&'a str),13 StarredBy(&'a str),
21 }14 }
22 15
23-/// The last activity time of `r`: its latest push, or its creation time.
24 const ACTIVITY: &str = "COALESCE((SELECT MAX(p.created_at) FROM push_events p \16 const ACTIVITY: &str = "COALESCE((SELECT MAX(p.created_at) FROM push_events p \
25 WHERE p.repo_id = r.id), r.created_at)";17 WHERE p.repo_id = r.id), r.created_at)";
26-/// The star count of `r`.
27 const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)";18 const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)";
28 19
29-/// The SQL condition under which a signed-in, non-admin viewer may read a private repo `r`, taking
30-/// the viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read:
31-/// the viewer's own repos, repos where the viewer is a collaborator, and repos of an org where the
32-/// viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member when the default
33-/// repo role is not `none`, or a member of a team covering the repo. Public repos are added by
34-/// the callers.
35 pub(crate) const VIEWER_ACCESS: &str = "(r.owner_id = ? \20 pub(crate) const VIEWER_ACCESS: &str = "(r.owner_id = ? \
36 OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \21 OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \
37 OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \22 OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \
@@ -44,10 +29,6 @@ pub(crate) const VIEWER_ACCESS: &str = "(r.owner_id = ? \
44 AND tr.repo_id = r.id))))))";29 AND tr.repo_id = r.id))))))";
45 30
46 impl Store {31 impl Store {
47- /// One page of a profile tab: the repos in `scope` that `viewer` may read, optionally
48- /// filtered by `query` (a case-insensitive substring of the name; `%`, `_` and `\` are
49- /// literal), in `sort` order. Rows carry the star count and the last activity time. A page
50- /// past the end is clamped to the last page. Returns the rows and the number of matches.
51 pub async fn list_visible_repos(32 pub async fn list_visible_repos(
52 &self,33 &self,
53 scope: RepoScope<'_>,34 scope: RepoScope<'_>,
@@ -73,7 +54,6 @@ impl Store {
73 .await54 .await
74 }55 }
75 56
76- /// How many repos in `scope` the viewer may read, with no name filter (the tab counts).
77 pub async fn count_visible_repos(57 pub async fn count_visible_repos(
78 &self,58 &self,
79 scope: RepoScope<'_>,59 scope: RepoScope<'_>,
@@ -84,10 +64,6 @@ impl Store {
84 count_repos(&conn, from_sql, &clauses.join(" AND "), params).await64 count_repos(&conn, from_sql, &clauses.join(" AND "), params).await
85 }65 }
86 66
87- /// Up to `limit` repos the signed-in `viewer` is part of: their own, ones they collaborate on, and
88- /// org repos they reach. Sorted by owner and name, for the command palette. Other public repos are
89- /// left out (Explore lists them), and so are an admin's: on a big instance they would push the
90- /// viewer's own repos past the limit. The rule is `VIEWER_ACCESS`.
91 pub async fn list_viewer_repos(&self, viewer: &User, limit: u64) -> Result<Vec<Repo>> {67 pub async fn list_viewer_repos(&self, viewer: &User, limit: u64) -> Result<Vec<Repo>> {
92 let mut params: Vec<Value> = (0..4).map(|_| Value::Text(viewer.id.clone())).collect();68 let mut params: Vec<Value> = (0..4).map(|_| Value::Text(viewer.id.clone())).collect();
93 let limit = i64::try_from(limit).unwrap_or(i64::MAX);69 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
@@ -105,9 +81,6 @@ impl Store {
105 .await81 .await
106 }82 }
107 83
108- /// One page of the repos `from_sql` (which joins `repos r` and its owner `users u`) yields
109- /// under `where_sql`, in `sort` order, with the total match count. `page` is 1-based and is
110- /// clamped to the last page; `per_page` to 1..=100.
111 pub(super) async fn page_of_repos(84 pub(super) async fn page_of_repos(
112 &self,85 &self,
113 from_sql: &str,86 from_sql: &str,
@@ -167,7 +140,6 @@ async fn count_repos(
167 Ok(u64::try_from(n).unwrap_or(0))140 Ok(u64::try_from(n).unwrap_or(0))
168 }141 }
169 142
170-/// The FROM clause, the WHERE clauses and their parameters for `scope` as seen by `viewer`.
171 fn scoped(scope: RepoScope<'_>, viewer: Option<&User>) -> (&'static str, Vec<String>, Vec<Value>) {143 fn scoped(scope: RepoScope<'_>, viewer: Option<&User>) -> (&'static str, Vec<String>, Vec<Value>) {
172 let (from_sql, scope_id) = match scope {144 let (from_sql, scope_id) = match scope {
173 RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id),145 RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id),
@@ -182,7 +154,6 @@ fn scoped(scope: RepoScope<'_>, viewer: Option<&User>) -> (&'static str, Vec<Str
182 }];154 }];
183 let mut params = vec![Value::Text(scope_id.to_owned())];155 let mut params = vec![Value::Text(scope_id.to_owned())];
184 match viewer {156 match viewer {
185- // Admins read everything.
186 Some(user) if user.is_admin => {}157 Some(user) if user.is_admin => {}
187 Some(user) => {158 Some(user) => {
188 clauses.push(format!("(r.visibility = 'public' OR {VIEWER_ACCESS})"));159 clauses.push(format!("(r.visibility = 'public' OR {VIEWER_ACCESS})"));
@@ -220,7 +191,6 @@ mod tests {
220 rows.into_iter().map(|(repo, _, _)| repo.name).collect()191 rows.into_iter().map(|(repo, _, _)| repo.name).collect()
221 }192 }
222 193
223- /// Tahinli owns `open` (public), `closed` and `shared` (private).
224 async fn fixture() -> Fixture {194 async fn fixture() -> Fixture {
225 let dir = tempfile::tempdir().unwrap();195 let dir = tempfile::tempdir().unwrap();
226 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();196 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
@@ -296,8 +266,6 @@ mod tests {
296 );266 );
297 }267 }
298 268
299- /// The org repos `viewer` sees are `expected`, and the SQL rule agrees with `authorize` on
300- /// every org repo.
301 async fn check_org(store: &Store, org_id: &str, viewer: User, expected: &[&str]) {269 async fn check_org(store: &Store, org_id: &str, viewer: User, expected: &[&str]) {
302 let got = names(store, RepoScope::OwnedBy(org_id), Some(&viewer)).await;270 let got = names(store, RepoScope::OwnedBy(org_id), Some(&viewer)).await;
303 assert_eq!(got, expected, "viewer {}", viewer.username);271 assert_eq!(got, expected, "viewer {}", viewer.username);
@@ -341,12 +309,10 @@ mod tests {
341 check_org(&fx.store, &org.id, viewer.clone(), expected)309 check_org(&fx.store, &org.id, viewer.clone(), expected)
342 };310 };
343 311
344- // The default repo role is read: every member sees every org repo.
345 check(&member, &["infra", "web"]).await;312 check(&member, &["infra", "web"]).await;
346 check(&outsider, &[]).await;313 check(&outsider, &[]).await;
347 check(&fx.owner, &["infra", "web"]).await;314 check(&fx.owner, &["infra", "web"]).await;
348 315
349- // With no default role, a plain member sees only what a team grants.
350 fx.store316 fx.store
351 .set_org_settings(317 .set_org_settings(
352 &org.id,318 &org.id,
@@ -371,9 +337,7 @@ mod tests {
371 let infra = repo_id(&fx.store, "acme", "infra").await;337 let infra = repo_id(&fx.store, "acme", "infra").await;
372 fx.store.add_team_repo(&team.id, &infra).await.unwrap();338 fx.store.add_team_repo(&team.id, &infra).await.unwrap();
373 check(&member, &["infra"]).await;339 check(&member, &["infra"]).await;
374- // An org owner sees every org repo whatever the default.
375 check(&fx.owner, &["infra", "web"]).await;340 check(&fx.owner, &["infra", "web"]).await;
376- // A team membership alone, without org membership, grants nothing.
377 fx.store.add_team_member(&team.id, &outsider.id).await.ok();341 fx.store.add_team_member(&team.id, &outsider.id).await.ok();
378 check(&outsider, &[]).await;342 check(&outsider, &[]).await;
379 }343 }
@@ -404,14 +368,11 @@ mod tests {
404 .list_visible_repos(owned, Some(&fx.owner), Some("O"), RepoSort::Name, 9, 1)368 .list_visible_repos(owned, Some(&fx.owner), Some("O"), RepoSort::Name, 9, 1)
405 .await369 .await
406 .unwrap();370 .unwrap();
407- // "closed" and "open" match; page 9 of 2 is clamped to the last page.
408 assert_eq!(total, 2);371 assert_eq!(total, 2);
409 assert_eq!(rows.len(), 1);372 assert_eq!(rows.len(), 1);
410 assert_eq!(rows[0].0.name, "open");373 assert_eq!(rows[0].0.name, "open");
411 }374 }
412 375
413- // The listing rules share one fixture; each check only adds what it needs,
414- // and the collaborator grant runs before the later checks.
415 #[tokio::test]376 #[tokio::test]
416 async fn repo_visibility_and_listing_rules() {377 async fn repo_visibility_and_listing_rules() {
417 let fx = fixture().await;378 let fx = fixture().await;
crates/forge-core/src/store/review_requests.rsmodified+0 -11
@@ -1,14 +1,9 @@
1-//! Review requests on pull requests: who was asked to review, by whom. A request is cleared when
2-//! the reviewer submits a review (`submit_review` does it in the same transaction) or when it is
3-//! withdrawn. Deleting a pull request removes its requests through the foreign key.
4-
5 use std::collections::HashMap;1 use std::collections::HashMap;
6 2
7 use super::{IN_CHUNK, Store, col_text, db_err, fetch_all, placeholders};3 use super::{IN_CHUNK, Store, col_text, db_err, fetch_all, placeholders};
8 use crate::error::Result;4 use crate::error::Result;
9 use crate::time::now_stamp;5 use crate::time::now_stamp;
10 6
11-/// A pending request as the global "Review requests" view lists it.
12 #[derive(Debug, Clone)]7 #[derive(Debug, Clone)]
13 pub struct ReviewRequestItem {8 pub struct ReviewRequestItem {
14 pub repo_owner: String,9 pub repo_owner: String,
@@ -20,7 +15,6 @@ pub struct ReviewRequestItem {
20 }15 }
21 16
22 impl Store {17 impl Store {
23- /// Asks `reviewer_id` to review. Returns `false` when a request is already pending.
24 pub async fn request_review(18 pub async fn request_review(
25 &self,19 &self,
26 issue_id: &str,20 issue_id: &str,
@@ -44,7 +38,6 @@ impl Store {
44 Ok(n == 1)38 Ok(n == 1)
45 }39 }
46 40
47- /// Withdraws a pending request. Returns whether there was one.
48 pub async fn withdraw_review_request(&self, issue_id: &str, reviewer_id: &str) -> Result<bool> {41 pub async fn withdraw_review_request(&self, issue_id: &str, reviewer_id: &str) -> Result<bool> {
49 let conn = self.inner.conn.lock().await;42 let conn = self.inner.conn.lock().await;
50 let n = conn43 let n = conn
@@ -57,7 +50,6 @@ impl Store {
57 Ok(n > 0)50 Ok(n > 0)
58 }51 }
59 52
60- /// Usernames with a pending request on the pull request, oldest request first.
61 pub async fn requested_reviewers(&self, issue_id: &str) -> Result<Vec<String>> {53 pub async fn requested_reviewers(&self, issue_id: &str) -> Result<Vec<String>> {
62 let mut map = self54 let mut map = self
63 .requested_reviewers_for(std::slice::from_ref(&issue_id.to_string()))55 .requested_reviewers_for(std::slice::from_ref(&issue_id.to_string()))
@@ -65,8 +57,6 @@ impl Store {
65 Ok(map.remove(issue_id).unwrap_or_default())57 Ok(map.remove(issue_id).unwrap_or_default())
66 }58 }
67 59
68- /// Pending reviewer usernames for each of `ids`, in one query. Pulls without requests have
69- /// no entry.
70 pub async fn requested_reviewers_for(60 pub async fn requested_reviewers_for(
71 &self,61 &self,
72 ids: &[String],62 ids: &[String],
@@ -96,7 +86,6 @@ impl Store {
96 Ok(out)86 Ok(out)
97 }87 }
98 88
99- /// Open pull requests where the user has a pending request, newest request first.
100 pub async fn review_requests_for_user(&self, user_id: &str) -> Result<Vec<ReviewRequestItem>> {89 pub async fn review_requests_for_user(&self, user_id: &str) -> Result<Vec<ReviewRequestItem>> {
101 let conn = self.read_conn().await;90 let conn = self.read_conn().await;
102 fetch_all(91 fetch_all(
crates/forge-core/src/store/reviews.rsmodified+0 -52
@@ -1,7 +1,3 @@
1-//! Pull request reviews and line comments. A review belongs to a pull request (an issues row
2-//! with `kind = 'pull'`). Every multi-row write runs in one transaction. Replies are submitted
3-//! at once through an auto-created `commented` review with no body.
4-
5 use std::collections::{BTreeMap, HashMap};1 use std::collections::{BTreeMap, HashMap};
6 2
7 use serde_json::json;3 use serde_json::json;
@@ -45,7 +41,6 @@ fn map_review(row: &Row) -> Result<Review> {
45 })41 })
46 }42 }
47 43
48-/// Reads `COMMENT_COLS`.
49 fn map_comment(row: &Row) -> Result<ReviewComment> {44 fn map_comment(row: &Row) -> Result<ReviewComment> {
50 let line = u32::try_from(col_int(row, 6)?)45 let line = u32::try_from(col_int(row, 6)?)
51 .map_err(|_| Error::Database("review comment line is out of range".into()))?;46 .map_err(|_| Error::Database("review comment line is out of range".into()))?;
@@ -69,7 +64,6 @@ fn map_comment(row: &Row) -> Result<ReviewComment> {
69 })64 })
70 }65 }
71 66
72-/// Same limits as issue comments: non-empty after trimming, at most `MAX_BODY` bytes.
73 fn validate_comment_body(body: &str) -> Result<()> {67 fn validate_comment_body(body: &str) -> Result<()> {
74 validate_body(body)?;68 validate_body(body)?;
75 if body.trim().is_empty() {69 if body.trim().is_empty() {
@@ -78,7 +72,6 @@ fn validate_comment_body(body: &str) -> Result<()> {
78 Ok(())72 Ok(())
79 }73 }
80 74
81-/// A full lowercase hex commit id (SHA-1 or SHA-256 length).
82 fn validate_oid(oid: &str) -> Result<()> {75 fn validate_oid(oid: &str) -> Result<()> {
83 let hex = oid76 let hex = oid
84 .bytes()77 .bytes()
@@ -90,7 +83,6 @@ fn validate_oid(oid: &str) -> Result<()> {
90 }83 }
91 }84 }
92 85
93-/// A repo-relative path: non-empty, no NUL, not absolute, no `..` segments.
94 fn validate_path(path: &str) -> Result<()> {86 fn validate_path(path: &str) -> Result<()> {
95 let bad = path.is_empty()87 let bad = path.is_empty()
96 || path.contains('\0')88 || path.contains('\0')
@@ -102,7 +94,6 @@ fn validate_path(path: &str) -> Result<()> {
102 Ok(())94 Ok(())
103 }95 }
104 96
105-/// The author of the pull request, or `NotFound` if the issue is not a pull request.
106 async fn pull_author(conn: &Connection, issue_id: &str) -> Result<String> {97 async fn pull_author(conn: &Connection, issue_id: &str) -> Result<String> {
107 fetch_opt(98 fetch_opt(
108 conn,99 conn,
@@ -125,7 +116,6 @@ async fn review_by_id(conn: &Connection, id: &str) -> Result<Option<Review>> {
125 .await116 .await
126 }117 }
127 118
128-/// The author's pending review on a pull request, if there is one.
129 async fn pending_of(conn: &Connection, issue_id: &str, author_id: &str) -> Result<Option<Review>> {119 async fn pending_of(conn: &Connection, issue_id: &str, author_id: &str) -> Result<Option<Review>> {
130 fetch_opt(120 fetch_opt(
131 conn,121 conn,
@@ -149,8 +139,6 @@ async fn comment_by_id(conn: &Connection, id: &str) -> Result<Option<ReviewComme
149 .await139 .await
150 }140 }
151 141
152-/// A submitted root comment of this pull request, or `NotFound`. Replies and comments in
153-/// pending reviews are not roots for this purpose.
154 async fn submitted_root(conn: &Connection, issue_id: &str, root_id: &str) -> Result<ReviewComment> {142 async fn submitted_root(conn: &Connection, issue_id: &str, root_id: &str) -> Result<ReviewComment> {
155 fetch_opt(143 fetch_opt(
156 conn,144 conn,
@@ -209,7 +197,6 @@ async fn insert_review(
209 Ok(id)197 Ok(id)
210 }198 }
211 199
212-/// Everything a new review comment stores, so the insert takes one argument.
213 struct NewComment<'a> {200 struct NewComment<'a> {
214 review_id: &'a str,201 review_id: &'a str,
215 issue_id: &'a str,202 issue_id: &'a str,
@@ -250,7 +237,6 @@ async fn insert_comment(conn: &Connection, c: NewComment<'_>) -> Result<String>
250 Ok(id)237 Ok(id)
251 }238 }
252 239
253-/// Deletes a review, its comments and their edit history. The caller has checked the review.
254 async fn delete_review_rows(conn: &Connection, review_id: &str) -> Result<()> {240 async fn delete_review_rows(conn: &Connection, review_id: &str) -> Result<()> {
255 let id = review_id.to_string();241 let id = review_id.to_string();
256 conn.execute(242 conn.execute(
@@ -272,8 +258,6 @@ async fn delete_review_rows(conn: &Connection, review_id: &str) -> Result<()> {
272 Ok(())258 Ok(())
273 }259 }
274 260
275-/// Review deletion for pull request reviews. Called from `Store::delete_repo` inside its
276-/// transaction, before the issue rows go. Child rows go before their parents.
277 pub(super) async fn delete_repo_review_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {261 pub(super) async fn delete_repo_review_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> {
278 let id = repo_id.to_string();262 let id = repo_id.to_string();
279 for sql in [263 for sql in [
@@ -288,14 +272,11 @@ pub(super) async fn delete_repo_review_rows(tx: &Transaction<'_>, repo_id: &str)
288 }272 }
289 273
290 impl Store {274 impl Store {
291- /// The author's pending review on a pull request, if any.
292 pub async fn pending_review(&self, issue_id: &str, author_id: &str) -> Result<Option<Review>> {275 pub async fn pending_review(&self, issue_id: &str, author_id: &str) -> Result<Option<Review>> {
293 let conn = self.read_conn().await;276 let conn = self.read_conn().await;
294 pending_of(&conn, issue_id, author_id).await277 pending_of(&conn, issue_id, author_id).await
295 }278 }
296 279
297- /// Adds a line comment. With `pending`, it goes into the author's pending review, which is
298- /// created if needed. Otherwise it goes into a new submitted `commented` review of its own.
299 #[allow(clippy::too_many_arguments)]280 #[allow(clippy::too_many_arguments)]
300 pub async fn add_review_comment(281 pub async fn add_review_comment(
301 &self,282 &self,
@@ -372,8 +353,6 @@ impl Store {
372 finish(tx, outcome).await353 finish(tx, outcome).await
373 }354 }
374 355
375- /// Replies to a submitted root comment. The reply copies the root's path, side, line and
376- /// commit, and is submitted at once through a new `commented` review without a body.
377 pub async fn reply_review_comment(356 pub async fn reply_review_comment(
378 &self,357 &self,
379 issue_id: &str,358 issue_id: &str,
@@ -421,9 +400,6 @@ impl Store {
421 finish(tx, outcome).await400 finish(tx, outcome).await
422 }401 }
423 402
424- /// Turns the author's pending review into `state`, or creates a review with no comments if
425- /// there is none. A `commented` review needs a body or at least one pending comment. The
426- /// pull request author cannot approve or request changes on their own pull request.
427 pub async fn submit_review(403 pub async fn submit_review(
428 &self,404 &self,
429 issue_id: &str,405 issue_id: &str,
@@ -498,7 +474,6 @@ impl Store {
498 finish(tx, outcome).await474 finish(tx, outcome).await
499 }475 }
500 476
501- /// Deletes the author's pending review and its comments. Does nothing if there is none.
502 pub async fn discard_pending_review(&self, issue_id: &str, author_id: &str) -> Result<()> {477 pub async fn discard_pending_review(&self, issue_id: &str, author_id: &str) -> Result<()> {
503 let conn = self.inner.conn.lock().await;478 let conn = self.inner.conn.lock().await;
504 let tx = conn.unchecked_transaction().await.map_err(db_err)?;479 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -512,8 +487,6 @@ impl Store {
512 finish(tx, outcome).await487 finish(tx, outcome).await
513 }488 }
514 489
515- /// Dismisses an approval or a change request, recording the reason and a `review_dismissed`
516- /// event. Write access is checked by the caller.
517 pub async fn dismiss_review(490 pub async fn dismiss_review(
518 &self,491 &self,
519 review_id: &str,492 review_id: &str,
@@ -561,7 +534,6 @@ impl Store {
561 finish(tx, outcome).await534 finish(tx, outcome).await
562 }535 }
563 536
564- /// Submitted reviews (dismissed ones included), oldest first.
565 pub async fn list_reviews(&self, issue_id: &str) -> Result<Vec<Review>> {537 pub async fn list_reviews(&self, issue_id: &str) -> Result<Vec<Review>> {
566 let conn = self.read_conn().await;538 let conn = self.read_conn().await;
567 fetch_all(539 fetch_all(
@@ -576,8 +548,6 @@ impl Store {
576 .await548 .await
577 }549 }
578 550
579- /// Threads of a pull request: submitted comments, plus the viewer's own pending ones.
580- /// Outdated threads are included; the caller decides how to show them.
581 pub async fn review_threads(551 pub async fn review_threads(
582 &self,552 &self,
583 issue_id: &str,553 issue_id: &str,
@@ -617,8 +587,6 @@ impl Store {
617 comment_by_id(&conn, id).await587 comment_by_id(&conn, id).await
618 }588 }
619 589
620- /// Replaces a comment's body, saving the previous one in the edit history. Only the comment's
621- /// author edits, so the author is recorded as the editor.
622 pub async fn edit_review_comment(&self, id: &str, body: &str) -> Result<()> {590 pub async fn edit_review_comment(&self, id: &str, body: &str) -> Result<()> {
623 validate_comment_body(body)?;591 validate_comment_body(body)?;
624 let conn = self.inner.conn.lock().await;592 let conn = self.inner.conn.lock().await;
@@ -651,8 +619,6 @@ impl Store {
651 finish(tx, outcome).await619 finish(tx, outcome).await
652 }620 }
653 621
654- /// Deletes a comment. Deleting a root deletes its replies too. A `commented` review left with
655- /// no body and no comments is removed with them.
656 pub async fn delete_review_comment(&self, id: &str) -> Result<()> {622 pub async fn delete_review_comment(&self, id: &str) -> Result<()> {
657 let conn = self.inner.conn.lock().await;623 let conn = self.inner.conn.lock().await;
658 let tx = conn.unchecked_transaction().await.map_err(db_err)?;624 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -693,9 +659,6 @@ impl Store {
693 finish(tx, outcome).await659 finish(tx, outcome).await
694 }660 }
695 661
696- /// Marks a thread resolved or not, recording who did and an event. Does nothing if the thread
697- /// already has that state. Only submitted root comments can be resolved; the caller checks
698- /// permissions.
699 pub async fn set_thread_resolved(662 pub async fn set_thread_resolved(
700 &self,663 &self,
701 root_id: &str,664 root_id: &str,
@@ -742,9 +705,6 @@ impl Store {
742 finish(tx, outcome).await705 finish(tx, outcome).await
743 }706 }
744 707
745- /// Moves a root comment and its replies to `line` at `commit_oid`, for when the line kept its
746- /// content but its number changed after a push. The diff hunk is kept. Only root comments
747- /// can be relocated; replies follow their root.
748 pub async fn relocate_review_comment(708 pub async fn relocate_review_comment(
749 &self,709 &self,
750 id: &str,710 id: &str,
@@ -774,8 +734,6 @@ impl Store {
774 finish(tx, outcome).await734 finish(tx, outcome).await
775 }735 }
776 736
777- /// Marks the given root comments of a pull request outdated. Ids that are not submitted
778- /// roots of that pull request are ignored.
779 pub async fn mark_outdated(&self, issue_id: &str, ids: &[String]) -> Result<()> {737 pub async fn mark_outdated(&self, issue_id: &str, ids: &[String]) -> Result<()> {
780 let conn = self.inner.conn.lock().await;738 let conn = self.inner.conn.lock().await;
781 let tx = conn.unchecked_transaction().await.map_err(db_err)?;739 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -796,9 +754,6 @@ impl Store {
796 finish(tx, outcome).await754 finish(tx, outcome).await
797 }755 }
798 756
799- /// Who approves and who requests changes. Each reviewer counts by their latest approval or
800- /// change request. Comment reviews and dismissed reviews are ignored, so a dismissed request
801- /// lets the reviewer's earlier, undismissed state count again.
802 pub async fn review_summary(&self, issue_id: &str) -> Result<ReviewSummary> {757 pub async fn review_summary(&self, issue_id: &str) -> Result<ReviewSummary> {
803 let mut summary = ReviewSummary::default();758 let mut summary = ReviewSummary::default();
804 for (_, name, state, _) in self.latest_review_states(issue_id).await? {759 for (_, name, state, _) in self.latest_review_states(issue_id).await? {
@@ -812,9 +767,6 @@ impl Store {
812 Ok(summary)767 Ok(summary)
813 }768 }
814 769
815- /// Each reviewer's latest non-commented, non-dismissed submitted state, as
816- /// `(author_id, username, state, commit_oid)`, ordered by author id. `commit_oid` is the head
817- /// the review was submitted on.
818 pub async fn latest_review_states(770 pub async fn latest_review_states(
819 &self,771 &self,
820 issue_id: &str,772 issue_id: &str,
@@ -865,7 +817,6 @@ mod tests {
865 _dir: tempfile::TempDir,817 _dir: tempfile::TempDir,
866 }818 }
867 819
868- /// Tahinli owns the repo; Bob and Carol review its pull requests.
869 async fn fixture() -> Fixture {820 async fn fixture() -> Fixture {
870 let dir = tempfile::tempdir().unwrap();821 let dir = tempfile::tempdir().unwrap();
871 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();822 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
@@ -892,8 +843,6 @@ mod tests {
892 }843 }
893 }844 }
894 845
895- /// Opens a pull request from `feature-{topic}` and returns its issue id.
896- /// Each scenario gets its own pull, so reviews never leak between them.
897 async fn new_pull(fx: &Fixture, topic: &str) -> String {846 async fn new_pull(fx: &Fixture, topic: &str) -> String {
898 let head = format!("feature-{topic}");847 let head = format!("feature-{topic}");
899 let pull = fx848 let pull = fx
@@ -914,7 +863,6 @@ mod tests {
914 pull.issue.id.clone()863 pull.issue.id.clone()
915 }864 }
916 865
917- /// A root comment on `src/lib.rs` line 3 at head `a`.
918 async fn comment(866 async fn comment(
919 fx: &Fixture,867 fx: &Fixture,
920 issue: &str,868 issue: &str,
crates/forge-core/src/store/server_settings.rsmodified+0 -8
@@ -1,7 +1,3 @@
1-//! Storage for the admin overrides of the server config (migration 0046). One row per dotted key.
2-//! The key set and the value rules live in `server_settings`; this layer only moves strings, and
3-//! seals the value of a secret field with the instance key.
4-
5 use std::collections::BTreeMap;1 use std::collections::BTreeMap;
6 2
7 use super::{Store, col_text, db_err, fetch_all, finish};3 use super::{Store, col_text, db_err, fetch_all, finish};
@@ -13,8 +9,6 @@ impl Store {
13 self.secret_key().map(|key| *key)9 self.secret_key().map(|key| *key)
14 }10 }
15 11
16- /// Every stored override, with secret values opened. A key this binary does not know is
17- /// skipped, so an override written by a newer version does not break an older one.
18 pub async fn server_overrides(&self) -> Result<BTreeMap<String, String>> {12 pub async fn server_overrides(&self) -> Result<BTreeMap<String, String>> {
19 let rows = {13 let rows = {
20 let conn = self.read_conn().await;14 let conn = self.read_conn().await;
@@ -40,7 +34,6 @@ impl Store {
40 Ok(out)34 Ok(out)
41 }35 }
42 36
43- /// Stores overrides, replacing any existing value for the same keys. Unknown keys are refused.
44 pub async fn set_server_overrides(&self, entries: &[(String, String)]) -> Result<()> {37 pub async fn set_server_overrides(&self, entries: &[(String, String)]) -> Result<()> {
45 let now = crate::time::now_stamp();38 let now = crate::time::now_stamp();
46 let mut prepared = Vec::with_capacity(entries.len());39 let mut prepared = Vec::with_capacity(entries.len());
@@ -72,7 +65,6 @@ impl Store {
72 finish(tx, outcome).await65 finish(tx, outcome).await
73 }66 }
74 67
75- /// Removes the override of `key`, so the file value (or the default) applies again.
76 pub async fn clear_server_override(&self, key: &str) -> Result<()> {68 pub async fn clear_server_override(&self, key: &str) -> Result<()> {
77 let conn = self.inner.conn.lock().await;69 let conn = self.inner.conn.lock().await;
78 conn.execute(70 conn.execute(
crates/forge-core/src/store/shell_activity.rsmodified+0 -46
@@ -1,6 +1,3 @@
1-//! Read-only queries behind the sidebar "profile corner": the signed-in user's inbox counts, the
2-//! items waiting on them, and the state of their own CI runs. Nothing here writes.
3-
4 use std::time::Duration;1 use std::time::Duration;
5 2
6 use turso::{Row, Value};3 use turso::{Row, Value};
@@ -13,78 +10,47 @@ use crate::error::{Error, Result};
13 use crate::notifications::Reason;10 use crate::notifications::Reason;
14 use crate::time::stamp_ago;11 use crate::time::stamp_ago;
15 12
16-/// Most runs each of `ActorRuns::running` and `ActorRuns::finished` lists: enough for the strip's
17-/// counts and list, bounded when runs pile up in the queue with no runner online.
18 const MAX_ACTOR_RUNS: i64 = 100;13 const MAX_ACTOR_RUNS: i64 = 100;
19 14
20-/// Unread inbox rows of the two kinds the corner shows.
21 #[derive(Debug, Clone, Copy, Default)]15 #[derive(Debug, Clone, Copy, Default)]
22 pub struct InboxKinds {16 pub struct InboxKinds {
23- /// Unread review requests.
24 pub reviews: u64,17 pub reviews: u64,
25- /// Unread mentions.
26 pub mentions: u64,18 pub mentions: u64,
27 }19 }
28 20
29-/// An unread inbox row that is waiting on the user, as the corner lists it.
30 #[derive(Debug, Clone)]21 #[derive(Debug, Clone)]
31 pub struct WaitingItem {22 pub struct WaitingItem {
32- /// Owner username of the repo.
33 pub owner: String,23 pub owner: String,
34- /// Repo name.
35 pub repo: String,24 pub repo: String,
36- /// Issue or pull number.
37 pub number: i64,25 pub number: i64,
38- /// True when the number is a pull request.
39 pub is_pull: bool,26 pub is_pull: bool,
40- /// Title of the issue or pull.
41 pub title: String,27 pub title: String,
42- /// Why the user was notified (`ReviewRequested` or `Mention`).
43 pub reason: Reason,28 pub reason: Reason,
44- /// When the inbox row last changed.
45 pub updated_at: String,29 pub updated_at: String,
46 }30 }
47 31
48-/// The user's own CI runs, as the corner shows them.
49 #[derive(Debug, Clone)]32 #[derive(Debug, Clone)]
50 pub struct ActorRuns {33 pub struct ActorRuns {
51- /// Queued or running runs, newest first, at most 100.
52 pub running: Vec<ActorRun>,34 pub running: Vec<ActorRun>,
53- /// Runs that finished within the caller's window, newest first, at most 100.
54 pub finished: Vec<ActorRun>,35 pub finished: Vec<ActorRun>,
55- /// Refs whose newest run by this user failed within the last 7 days.
56 pub failing: u64,36 pub failing: u64,
57- /// The newest of those failed runs as (owner, repo, run number), for a link straight to it.
58 pub newest_failing: Option<(String, String, i64)>,37 pub newest_failing: Option<(String, String, i64)>,
59 }38 }
60 39
61-/// One CI run of the user, with its job progress.
62 #[derive(Debug, Clone)]40 #[derive(Debug, Clone)]
63 pub struct ActorRun {41 pub struct ActorRun {
64- /// Owner username of the repo.
65 pub owner: String,42 pub owner: String,
66- /// Repo name.
67 pub repo: String,43 pub repo: String,
68- /// Run number within the repo.
69 pub number: i64,44 pub number: i64,
70- /// Git ref the run ran on.
71 pub git_ref: String,45 pub git_ref: String,
72- /// Current run state.
73 pub state: RunState,46 pub state: RunState,
74- /// When the run was created.
75 pub created_at: String,47 pub created_at: String,
76- /// When the run finished, if it has.
77 pub finished_at: Option<String>,48 pub finished_at: Option<String>,
78- /// Jobs the run has.
79 pub jobs_total: u64,49 pub jobs_total: u64,
80- /// Jobs in a final state (success, failure, cancelled, error or skipped).
81 pub jobs_done: u64,50 pub jobs_done: u64,
82- /// Name of one job that is running now, if any.
83 pub current_job: Option<String>,51 pub current_job: Option<String>,
84 }52 }
85 53
86-/// Runs one row per run: owner, repo, number, ref, state, times, job counts and a running job.
87-/// The caller appends the WHERE, ORDER BY and LIMIT.
88 const ACTOR_RUN_SELECT: &str = "SELECT o.username, r.name, ci_runs.number, ci_runs.git_ref, \54 const ACTOR_RUN_SELECT: &str = "SELECT o.username, r.name, ci_runs.number, ci_runs.git_ref, \
89 ci_runs.state, ci_runs.created_at, ci_runs.finished_at, \55 ci_runs.state, ci_runs.created_at, ci_runs.finished_at, \
90 (SELECT COUNT(*) FROM ci_jobs j WHERE j.run_id = ci_runs.id), \56 (SELECT COUNT(*) FROM ci_jobs j WHERE j.run_id = ci_runs.id), \
@@ -96,12 +62,10 @@ const ACTOR_RUN_SELECT: &str = "SELECT o.username, r.name, ci_runs.number, ci_ru
96 JOIN repos r ON r.id = ci_runs.repo_id \62 JOIN repos r ON r.id = ci_runs.repo_id \
97 JOIN users o ON o.id = r.owner_id";63 JOIN users o ON o.id = r.owner_id";
98 64
99-/// A count column as `u64`. Counts are never negative, so a negative value is a database error.
100 fn count_from(n: i64) -> Result<u64> {65 fn count_from(n: i64) -> Result<u64> {
101 u64::try_from(n).map_err(|_| Error::Database("negative count".into()))66 u64::try_from(n).map_err(|_| Error::Database("negative count".into()))
102 }67 }
103 68
104-/// Maps a row of `ACTOR_RUN_SELECT`.
105 fn map_actor_run(row: &Row) -> Result<ActorRun> {69 fn map_actor_run(row: &Row) -> Result<ActorRun> {
106 Ok(ActorRun {70 Ok(ActorRun {
107 owner: col_text(row, 0)?,71 owner: col_text(row, 0)?,
@@ -118,7 +82,6 @@ fn map_actor_run(row: &Row) -> Result<ActorRun> {
118 }82 }
119 83
120 impl Store {84 impl Store {
121- /// Unread review requests and mentions in the user's inbox, in repos the user can still read.
122 pub async fn inbox_kind_counts(&self, user_id: &str) -> Result<InboxKinds> {85 pub async fn inbox_kind_counts(&self, user_id: &str) -> Result<InboxKinds> {
123 let readable = readable_repo();86 let readable = readable_repo();
124 let sql = format!(87 let sql = format!(
@@ -145,7 +108,6 @@ impl Store {
145 Ok(kinds)108 Ok(kinds)
146 }109 }
147 110
148- /// The user's newest unread review requests and mentions, newest first, at most `limit`.
149 pub async fn waiting_on(&self, user_id: &str, limit: u64) -> Result<Vec<WaitingItem>> {111 pub async fn waiting_on(&self, user_id: &str, limit: u64) -> Result<Vec<WaitingItem>> {
150 let readable = readable_repo();112 let readable = readable_repo();
151 let sql = format!(113 let sql = format!(
@@ -180,11 +142,7 @@ impl Store {
180 .await142 .await
181 }143 }
182 144
183- /// The user's own CI runs: those still queued or running, those that finished within the last
184- /// `recent_secs` seconds, and how many refs are failing on their newest run.
185 pub async fn actor_runs(&self, actor_id: &str, recent_secs: i64) -> Result<ActorRuns> {145 pub async fn actor_runs(&self, actor_id: &str, recent_secs: i64) -> Result<ActorRuns> {
186- // Every query binds the viewer's readable-repo filter, so a run in a repo the actor can no
187- // longer read is left out. The placeholders are all plain `?`, bound in SQL order.
188 let readable = readable_repo();146 let readable = readable_repo();
189 let conn = self.read_conn().await;147 let conn = self.read_conn().await;
190 let mut params = vec![Value::Text(actor_id.to_string())];148 let mut params = vec![Value::Text(actor_id.to_string())];
@@ -221,7 +179,6 @@ impl Store {
221 )179 )
222 .await?;180 .await?;
223 181
224- // The same failing runs `/needs-you` lists: counted, and the newest kept for its link.
225 let failing = fetch_all(182 let failing = fetch_all(
226 &conn,183 &conn,
227 &format!(184 &format!(
@@ -257,7 +214,6 @@ mod tests {
257 use crate::model::Visibility;214 use crate::model::Visibility;
258 use crate::time::now_stamp;215 use crate::time::now_stamp;
259 216
260- /// Inserts one CI run row directly, with the columns the queries read.
261 #[allow(clippy::too_many_arguments)]217 #[allow(clippy::too_many_arguments)]
262 async fn insert_run(218 async fn insert_run(
263 store: &Store,219 store: &Store,
@@ -291,7 +247,6 @@ mod tests {
291 .unwrap();247 .unwrap();
292 }248 }
293 249
294- /// Inserts one CI job row of a run.
295 async fn insert_job(store: &Store, id: &str, run_id: &str, name: &str, state: &str) {250 async fn insert_job(store: &Store, id: &str, run_id: &str, name: &str, state: &str) {
296 store251 store
297 .inner252 .inner
@@ -324,7 +279,6 @@ mod tests {
324 .await279 .await
325 .unwrap();280 .unwrap();
326 let hour_ago = stamp_ago(Duration::from_secs(3600));281 let hour_ago = stamp_ago(Duration::from_secs(3600));
327- // A failed run on dev an hour ago, and a running run on main with one job going.
328 insert_run(282 insert_run(
329 &store,283 &store,
330 "run1",284 "run1",
crates/forge-core/src/store/signatures.rsmodified+0 -18
@@ -1,6 +1,3 @@
1-//! Signed commit storage: GPG public keys users added, and the cached verification result of each
2-//! commit. The verification itself lives in forge-git (`verify.rs`) and forge-web (`signatures.rs`).
3-
4 use std::collections::HashMap;1 use std::collections::HashMap;
5 use std::str::FromStr;2 use std::str::FromStr;
6 3
@@ -16,7 +13,6 @@ use crate::time::now_stamp;
16 13
17 const GPG_COLS: &str = "id, user_id, fingerprint, armored, emails, created_at";14 const GPG_COLS: &str = "id, user_id, fingerprint, armored, emails, created_at";
18 15
19-/// A GPG public key a user added. `emails` are the uid addresses of the key.
20 #[derive(Debug, Clone, PartialEq, Eq)]16 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub struct GpgKey {17 pub struct GpgKey {
22 pub id: Id,18 pub id: Id,
@@ -27,7 +23,6 @@ pub struct GpgKey {
27 pub created_at: String,23 pub created_at: String,
28 }24 }
29 25
30-/// The stored verification result of one commit.
31 #[derive(Debug, Clone, PartialEq, Eq)]26 #[derive(Debug, Clone, PartialEq, Eq)]
32 pub struct CachedSig {27 pub struct CachedSig {
33 pub status: SigStatus,28 pub status: SigStatus,
@@ -131,7 +126,6 @@ fn map_cached(row: &turso::Row) -> Result<(String, CachedSig)> {
131 }126 }
132 127
133 impl Store {128 impl Store {
134- /// Stores a GPG key. `Conflict` if the fingerprint is already stored (for any user).
135 pub async fn add_gpg_key(129 pub async fn add_gpg_key(
136 &self,130 &self,
137 user_id: &str,131 user_id: &str,
@@ -178,7 +172,6 @@ impl Store {
178 .await172 .await
179 }173 }
180 174
181- /// Every stored GPG key, whoever owns it. Used to rebuild the managed keyring.
182 pub async fn all_gpg_keys(&self) -> Result<Vec<GpgKey>> {175 pub async fn all_gpg_keys(&self) -> Result<Vec<GpgKey>> {
183 let conn = self.read_conn().await;176 let conn = self.read_conn().await;
184 fetch_all(177 fetch_all(
@@ -201,8 +194,6 @@ impl Store {
201 .await194 .await
202 }195 }
203 196
204- /// Deletes the key only if it belongs to `user_id`. Returns the deleted key, or `None` when
205- /// the id is unknown or belongs to someone else.
206 pub async fn delete_gpg_key(&self, user_id: &str, id: &str) -> Result<Option<GpgKey>> {197 pub async fn delete_gpg_key(&self, user_id: &str, id: &str) -> Result<Option<GpgKey>> {
207 let conn = self.inner.conn.lock().await;198 let conn = self.inner.conn.lock().await;
208 let key = fetch_opt(199 let key = fetch_opt(
@@ -224,7 +215,6 @@ impl Store {
224 Ok(Some(key))215 Ok(Some(key))
225 }216 }
226 217
227- /// The SSH key with this `SHA256:` fingerprint, if any user registered it.
228 pub async fn ssh_key_by_fingerprint(&self, fingerprint: &str) -> Result<Option<SshKey>> {218 pub async fn ssh_key_by_fingerprint(&self, fingerprint: &str) -> Result<Option<SshKey>> {
229 let conn = self.read_conn().await;219 let conn = self.read_conn().await;
230 fetch_opt(220 fetch_opt(
@@ -236,7 +226,6 @@ impl Store {
236 .await226 .await
237 }227 }
238 228
239- /// Cached results for the given commit ids of one repo. Commits without a row are absent.
240 pub async fn cached_signatures(229 pub async fn cached_signatures(
241 &self,230 &self,
242 repo_id: &str,231 repo_id: &str,
@@ -258,7 +247,6 @@ impl Store {
258 Ok(rows.into_iter().collect())247 Ok(rows.into_iter().collect())
259 }248 }
260 249
261- /// Stores or replaces the result for one commit.
262 pub async fn put_signature(&self, repo_id: &str, oid: &str, sig: &CachedSig) -> Result<()> {250 pub async fn put_signature(&self, repo_id: &str, oid: &str, sig: &CachedSig) -> Result<()> {
263 let conn = self.inner.conn.lock().await;251 let conn = self.inner.conn.lock().await;
264 conn.execute(252 conn.execute(
@@ -280,8 +268,6 @@ impl Store {
280 Ok(())268 Ok(())
281 }269 }
282 270
283- /// Drops the cached results that a change of `user_id`'s keys can affect: rows signed by that
284- /// user, and every `unknown_key` row, since a new key may now match it.
285 pub async fn invalidate_signatures_for_user(&self, user_id: &str) -> Result<()> {271 pub async fn invalidate_signatures_for_user(&self, user_id: &str) -> Result<()> {
286 let conn = self.inner.conn.lock().await;272 let conn = self.inner.conn.lock().await;
287 conn.execute(273 conn.execute(
@@ -344,7 +330,6 @@ mod tests {
344 "duplicate fingerprint: {dup:?}"330 "duplicate fingerprint: {dup:?}"
345 );331 );
346 332
347- // Another user cannot delete the key; the owner can.
348 let bob = store.create_user("bob", None, "hash", false).await.unwrap();333 let bob = store.create_user("bob", None, "hash", false).await.unwrap();
349 assert!(334 assert!(
350 store335 store
@@ -395,7 +380,6 @@ mod tests {
395 .is_empty()380 .is_empty()
396 );381 );
397 382
398- // Replacing a row keeps one row per commit.
399 store383 store
400 .put_signature(&repo, &oids[0], &sig(SigStatus::Unverified, Some(&tahinli)))384 .put_signature(&repo, &oids[0], &sig(SigStatus::Unverified, Some(&tahinli)))
401 .await385 .await
@@ -408,7 +392,6 @@ mod tests {
408 .await392 .await
409 .unwrap();393 .unwrap();
410 let got = store.cached_signatures(&repo, &oids).await.unwrap();394 let got = store.cached_signatures(&repo, &oids).await.unwrap();
411- // signer rows and unknown_key rows are gone; the bad row stays.
412 assert_eq!(got.len(), 1);395 assert_eq!(got.len(), 1);
413 assert!(got.contains_key(&oids[2]));396 assert!(got.contains_key(&oids[2]));
414 }397 }
@@ -435,7 +418,6 @@ mod tests {
435 "round trip {k:?}"418 "round trip {k:?}"
436 );419 );
437 }420 }
438- // Stored in the signature cache, so the literals must not change.
439 for (s, literal) in [421 for (s, literal) in [
440 (SigStatus::Verified, "verified"),422 (SigStatus::Verified, "verified"),
441 (SigStatus::Unverified, "unverified"),423 (SigStatus::Unverified, "unverified"),
crates/forge-core/src/store/snapshot.rsmodified+0 -26
@@ -1,10 +1,3 @@
1-//! Consistent copies of the metadata database for backups, and read-only verification of them.
2-//!
3-//! Method: `VACUUM INTO`. Turso 0.8.3 implements `VACUUM INTO` (only the in-place `VACUUM` is
4-//! gated behind `experimental_vacuum`), and the test below proves the copy opens with its data.
5-//! The copy runs on the store's single connection while its mutex is held, so no other statement
6-//! through this store can interleave with it.
7-
8 use std::path::Path;1 use std::path::Path;
9 2
10 use turso::Builder;3 use turso::Builder;
@@ -14,15 +7,11 @@ use crate::error::{Error, Result};
14 use crate::store::Store;7 use crate::store::Store;
15 use crate::store::migrate::MIGRATIONS;8 use crate::store::migrate::MIGRATIONS;
16 9
17-/// The snapshot method in use. Recorded in the backup manifest.
18 pub const SNAPSHOT_METHOD: &str = "vacuum-into";10 pub const SNAPSHOT_METHOD: &str = "vacuum-into";
19 11
20-/// What [`verify_snapshot`] learned from a snapshot file.
21 #[derive(Debug, Clone, PartialEq, Eq)]12 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct SnapshotInfo {13 pub struct SnapshotInfo {
23- /// Highest applied migration version. Migrations are contiguous from 1 (checked).
24 pub schema_version: u32,14 pub schema_version: u32,
25- /// `(repo id, owner username, repo name)`, ordered by repo id.
26 pub repos: Vec<(String, String, String)>,15 pub repos: Vec<(String, String, String)>,
27 }16 }
28 17
@@ -39,8 +28,6 @@ fn utf8_path(path: &Path) -> Result<&str> {
39 }28 }
40 29
41 impl Store {30 impl Store {
42- /// Writes a consistent copy of the database to `dest` with `VACUUM INTO`, then fsyncs it.
43- /// `dest` must not exist. The store's connection is held for the whole copy.
44 pub async fn snapshot_to(&self, dest: &Path) -> Result<()> {31 pub async fn snapshot_to(&self, dest: &Path) -> Result<()> {
45 if std::fs::symlink_metadata(dest).is_ok() {32 if std::fs::symlink_metadata(dest).is_ok() {
46 return Err(Error::Conflict(format!(33 return Err(Error::Conflict(format!(
@@ -60,8 +47,6 @@ impl Store {
60 }47 }
61 48
62 impl Store {49 impl Store {
63- /// Runs `PRAGMA integrity_check` on the live database and returns its rows. A healthy
64- /// database gives exactly `["ok"]`; anything else lists the problems found.
65 pub async fn integrity_check(&self) -> Result<Vec<String>> {50 pub async fn integrity_check(&self) -> Result<Vec<String>> {
66 let conn = self.inner.conn.lock().await;51 let conn = self.inner.conn.lock().await;
67 fetch_all(&conn, "PRAGMA integrity_check", (), |row| {52 fetch_all(&conn, "PRAGMA integrity_check", (), |row| {
@@ -71,17 +56,12 @@ impl Store {
71 }56 }
72 }57 }
73 58
74-/// `VACUUM INTO` writes a WAL-mode file, so its rows may sit in a `-wal` sidecar. Turso does not
75-/// let the copy leave WAL mode (`journal_mode = DELETE` is ignored), so this checkpoints the copy
76-/// until every frame is in the main file, and then removes sidecars that are empty. A sidecar that
77-/// still has bytes is an error. The main file alone is then the whole database.
78 async fn make_self_contained(dest: &Path) -> Result<()> {59 async fn make_self_contained(dest: &Path) -> Result<()> {
79 let db = Builder::new_local(utf8_path(dest)?)60 let db = Builder::new_local(utf8_path(dest)?)
80 .build()61 .build()
81 .await62 .await
82 .map_err(db_err)?;63 .map_err(db_err)?;
83 let conn = db.connect().map_err(db_err)?;64 let conn = db.connect().map_err(db_err)?;
84- // Columns: busy, frames in the log, frames checkpointed.
85 let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| {65 let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| {
86 Ok((col_int(row, 0)?, col_int(row, 1)?, col_int(row, 2)?))66 Ok((col_int(row, 0)?, col_int(row, 1)?, col_int(row, 2)?))
87 })67 })
@@ -115,8 +95,6 @@ async fn make_self_contained(dest: &Path) -> Result<()> {
115 Ok(())95 Ok(())
116 }96 }
117 97
118-/// Opens a snapshot read-only with a fresh connection, runs `PRAGMA integrity_check`, checks the
119-/// migration history and the repo rows, and returns what it found. Any problem is an error.
120 pub async fn verify_snapshot(path: &Path) -> Result<SnapshotInfo> {98 pub async fn verify_snapshot(path: &Path) -> Result<SnapshotInfo> {
121 let db = Builder::new_local(utf8_path(path)?)99 let db = Builder::new_local(utf8_path(path)?)
122 .read_only(true)100 .read_only(true)
@@ -173,7 +151,6 @@ pub async fn verify_snapshot(path: &Path) -> Result<SnapshotInfo> {
173 |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_text(row, 2)?)),151 |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_text(row, 2)?)),
174 )152 )
175 .await?;153 .await?;
176- // A repo whose owner row is missing would drop out of the join; that is a broken snapshot.
177 if total.first().copied().unwrap_or(0) != i64::try_from(repos.len()).unwrap_or(-1) {154 if total.first().copied().unwrap_or(0) != i64::try_from(repos.len()).unwrap_or(-1) {
178 return Err(Error::Database(155 return Err(Error::Database(
179 "repos rows without a matching owner in users".into(),156 "repos rows without a matching owner in users".into(),
@@ -212,7 +189,6 @@ mod tests {
212 .await189 .await
213 .expect("repo");190 .expect("repo");
214 191
215- // Scenario: a snapshot holds all its data in the main file and opens read only.
216 let snap = dir.path().join("snap").join("forge.db");192 let snap = dir.path().join("snap").join("forge.db");
217 std::fs::create_dir_all(snap.parent().expect("parent")).expect("mkdir");193 std::fs::create_dir_all(snap.parent().expect("parent")).expect("mkdir");
218 store.snapshot_to(&snap).await.expect("snapshot");194 store.snapshot_to(&snap).await.expect("snapshot");
@@ -221,7 +197,6 @@ mod tests {
221 "an existing target must be refused"197 "an existing target must be refused"
222 );198 );
223 199
224- // The main file alone must hold everything: copy it to a fresh directory and verify.
225 let alone_dir = dir.path().join("alone");200 let alone_dir = dir.path().join("alone");
226 std::fs::create_dir_all(&alone_dir).expect("mkdir");201 std::fs::create_dir_all(&alone_dir).expect("mkdir");
227 let alone = alone_dir.join("forge.db");202 let alone = alone_dir.join("forge.db");
@@ -243,7 +218,6 @@ mod tests {
243 vec![(repo.id.clone(), "Tahinli".to_string(), "demo".to_string())]218 vec![(repo.id.clone(), "Tahinli".to_string(), "demo".to_string())]
244 );219 );
245 220
246- // Scenario: a garbage file and a truncated copy both fail verification.
247 let garbage = dir.path().join("garbage.db");221 let garbage = dir.path().join("garbage.db");
248 std::fs::write(&garbage, b"not a database at all, just text padding").expect("write");222 std::fs::write(&garbage, b"not a database at all, just text padding").expect("write");
249 assert!(223 assert!(
crates/forge-core/src/store/snippets.rsmodified+0 -34
@@ -1,7 +1,3 @@
1-//! Snippets: small collections of text files with a visibility and a revision history. Every
2-//! create and every save writes a revision that holds the whole file set as JSON. The rules
3-//! (limits, file names, visibility) live here so the web layer and the tests share them.
4-
5 use serde::{Deserialize, Serialize};1 use serde::{Deserialize, Serialize};
6 use turso::Connection;2 use turso::Connection;
7 3
@@ -9,18 +5,13 @@ use super::{Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, new_
9 use crate::error::{Error, Result};5 use crate::error::{Error, Result};
10 use crate::time::now_stamp;6 use crate::time::now_stamp;
11 7
12-/// Most files one snippet may hold.
13 pub const MAX_FILES: usize = 10;8 pub const MAX_FILES: usize = 10;
14-/// Largest total size of a snippet's file contents, in bytes.
15 pub const MAX_TOTAL_BYTES: usize = 1024 * 1024;9 pub const MAX_TOTAL_BYTES: usize = 1024 * 1024;
16 pub const MAX_TITLE_CHARS: usize = 120;10 pub const MAX_TITLE_CHARS: usize = 120;
17 pub const MAX_DESCRIPTION_CHARS: usize = 1000;11 pub const MAX_DESCRIPTION_CHARS: usize = 1000;
18 pub const MAX_FILE_NAME_CHARS: usize = 100;12 pub const MAX_FILE_NAME_CHARS: usize = 100;
19-/// Most snippets one list page returns.
20 const LIST_LIMIT: i64 = 200;13 const LIST_LIMIT: i64 = 200;
21 14
22-/// Who can see a snippet. `Public` is listed, `Unlisted` works by link only, `Private` is the
23-/// owner's alone.
24 #[derive(Debug, Clone, Copy, PartialEq, Eq)]15 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
25 pub enum SnippetVisibility {16 pub enum SnippetVisibility {
26 Public,17 Public,
@@ -51,7 +42,6 @@ impl SnippetVisibility {
51 }42 }
52 }43 }
53 44
54-/// One file of a snippet. The name is unique within the snippet.
55 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]45 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56 pub struct SnippetFile {46 pub struct SnippetFile {
57 pub name: String,47 pub name: String,
@@ -68,13 +58,10 @@ pub struct Snippet {
68 pub visibility: SnippetVisibility,58 pub visibility: SnippetVisibility,
69 pub created_at: String,59 pub created_at: String,
70 pub updated_at: String,60 pub updated_at: String,
71- /// Files in their saved order.
72 pub files: Vec<SnippetFile>,61 pub files: Vec<SnippetFile>,
73 }62 }
74 63
75 impl Snippet {64 impl Snippet {
76- /// Whether a viewer may read the snippet. The owner always may; anyone may read a public or
77- /// unlisted one, and nobody else may read a private one.
78 pub fn is_visible_to(&self, viewer_id: Option<&str>) -> bool {65 pub fn is_visible_to(&self, viewer_id: Option<&str>) -> bool {
79 self.visibility != SnippetVisibility::Private || viewer_id == Some(self.owner_id.as_str())66 self.visibility != SnippetVisibility::Private || viewer_id == Some(self.owner_id.as_str())
80 }67 }
@@ -84,7 +71,6 @@ impl Snippet {
84 }71 }
85 }72 }
86 73
87-/// A snippet as it appears in a list: no file contents.
88 #[derive(Debug, Clone, PartialEq, Eq)]74 #[derive(Debug, Clone, PartialEq, Eq)]
89 pub struct SnippetSummary {75 pub struct SnippetSummary {
90 pub id: String,76 pub id: String,
@@ -95,7 +81,6 @@ pub struct SnippetSummary {
95 pub file_count: u64,81 pub file_count: u64,
96 }82 }
97 83
98-/// One saved state of a snippet. `files` is the complete file set after that save.
99 #[derive(Debug, Clone, PartialEq, Eq)]84 #[derive(Debug, Clone, PartialEq, Eq)]
100 pub struct SnippetRevision {85 pub struct SnippetRevision {
101 pub id: String,86 pub id: String,
@@ -104,7 +89,6 @@ pub struct SnippetRevision {
104 pub files: Vec<SnippetFile>,89 pub files: Vec<SnippetFile>,
105 }90 }
106 91
107-/// Checks a file name: 1 to 100 characters from `[A-Za-z0-9._-]`, not starting with `.`.
108 pub fn validate_file_name(name: &str) -> Result<()> {92 pub fn validate_file_name(name: &str) -> Result<()> {
109 let count = name.chars().count();93 let count = name.chars().count();
110 if count == 0 || count > MAX_FILE_NAME_CHARS {94 if count == 0 || count > MAX_FILE_NAME_CHARS {
@@ -126,7 +110,6 @@ pub fn validate_file_name(name: &str) -> Result<()> {
126 Ok(())110 Ok(())
127 }111 }
128 112
129-/// Checks a title: not blank after trimming, and at most 120 characters.
130 pub fn validate_title(title: &str) -> Result<()> {113 pub fn validate_title(title: &str) -> Result<()> {
131 let trimmed = title.trim();114 let trimmed = title.trim();
132 if trimmed.is_empty() || trimmed.chars().count() > MAX_TITLE_CHARS {115 if trimmed.is_empty() || trimmed.chars().count() > MAX_TITLE_CHARS {
@@ -137,7 +120,6 @@ pub fn validate_title(title: &str) -> Result<()> {
137 Ok(())120 Ok(())
138 }121 }
139 122
140-/// Checks a description: at most 1000 characters.
141 pub fn validate_description(description: &str) -> Result<()> {123 pub fn validate_description(description: &str) -> Result<()> {
142 if description.trim().chars().count() > MAX_DESCRIPTION_CHARS {124 if description.trim().chars().count() > MAX_DESCRIPTION_CHARS {
143 return Err(Error::Invalid(format!(125 return Err(Error::Invalid(format!(
@@ -147,8 +129,6 @@ pub fn validate_description(description: &str) -> Result<()> {
147 Ok(())129 Ok(())
148 }130 }
149 131
150-/// Checks a whole file set: 1 to 10 files, valid and unique names, no NUL bytes, and at most
151-/// 1 MiB of content in total.
152 pub fn validate_files(files: &[SnippetFile]) -> Result<()> {132 pub fn validate_files(files: &[SnippetFile]) -> Result<()> {
153 if files.is_empty() {133 if files.is_empty() {
154 return Err(Error::Invalid("a snippet needs at least one file".into()));134 return Err(Error::Invalid("a snippet needs at least one file".into()));
@@ -202,7 +182,6 @@ fn map_snippet(row: &turso::Row) -> Result<Snippet> {
202 })182 })
203 }183 }
204 184
205-/// One row of the summary queries: id, owner name, title, visibility, update stamp, file count.
206 fn summary_row(row: &turso::Row) -> Result<SnippetSummary> {185 fn summary_row(row: &turso::Row) -> Result<SnippetSummary> {
207 let visibility = col_text(row, 3)?;186 let visibility = col_text(row, 3)?;
208 Ok(SnippetSummary {187 Ok(SnippetSummary {
@@ -265,7 +244,6 @@ async fn write_revision(
265 }244 }
266 245
267 impl Store {246 impl Store {
268- /// Creates a snippet owned by `owner_id` with its first revision. Inputs are checked first.
269 pub async fn create_snippet(247 pub async fn create_snippet(
270 &self,248 &self,
271 owner_id: &str,249 owner_id: &str,
@@ -305,8 +283,6 @@ impl Store {
305 self.get_snippet(&id).await?.ok_or(Error::NotFound)283 self.get_snippet(&id).await?.ok_or(Error::NotFound)
306 }284 }
307 285
308- /// Saves a new state of a snippet and records a revision. Only the owner may save: any other
309- /// `owner_id` gets `NotFound`, the same as an unknown snippet.
310 pub async fn update_snippet(286 pub async fn update_snippet(
311 &self,287 &self,
312 owner_id: &str,288 owner_id: &str,
@@ -356,8 +332,6 @@ impl Store {
356 self.get_snippet(snippet_id).await?.ok_or(Error::NotFound)332 self.get_snippet(snippet_id).await?.ok_or(Error::NotFound)
357 }333 }
358 334
359- /// Deletes a snippet with its files and revisions. Returns `false` when the owner does not
360- /// match or the snippet does not exist.
361 pub async fn delete_snippet(&self, owner_id: &str, snippet_id: &str) -> Result<bool> {335 pub async fn delete_snippet(&self, owner_id: &str, snippet_id: &str) -> Result<bool> {
362 let conn = self.inner.conn.lock().await;336 let conn = self.inner.conn.lock().await;
363 let tx = conn.unchecked_transaction().await.map_err(db_err)?;337 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -387,7 +361,6 @@ impl Store {
387 finish(tx, outcome).await361 finish(tx, outcome).await
388 }362 }
389 363
390- /// One snippet with its files, or `None`. Visibility is not checked here; callers decide.
391 pub async fn get_snippet(&self, snippet_id: &str) -> Result<Option<Snippet>> {364 pub async fn get_snippet(&self, snippet_id: &str) -> Result<Option<Snippet>> {
392 let conn = self.read_conn().await;365 let conn = self.read_conn().await;
393 let Some(mut snippet) = fetch_opt(366 let Some(mut snippet) = fetch_opt(
@@ -413,8 +386,6 @@ impl Store {
413 Ok(Some(snippet))386 Ok(Some(snippet))
414 }387 }
415 388
416- /// Snippets a viewer can list: every public one, plus all of the viewer's own. `None` lists
417- /// only the public ones. Newest first.
418 pub async fn list_snippets(&self, viewer_id: Option<&str>) -> Result<Vec<SnippetSummary>> {389 pub async fn list_snippets(&self, viewer_id: Option<&str>) -> Result<Vec<SnippetSummary>> {
419 let conn = self.read_conn().await;390 let conn = self.read_conn().await;
420 fetch_all(391 fetch_all(
@@ -430,8 +401,6 @@ impl Store {
430 .await401 .await
431 }402 }
432 403
433- /// The snippets `owner_id` owns that the viewer can list: their public ones, and all of them
434- /// when the viewer is the owner. Unlisted ones are left out, as on `list_snippets`. Newest first.
435 pub async fn list_owner_snippets(404 pub async fn list_owner_snippets(
436 &self,405 &self,
437 owner_id: &str,406 owner_id: &str,
@@ -455,7 +424,6 @@ impl Store {
455 .await424 .await
456 }425 }
457 426
458- /// Every revision of a snippet, oldest first.
459 pub async fn list_snippet_revisions(&self, snippet_id: &str) -> Result<Vec<SnippetRevision>> {427 pub async fn list_snippet_revisions(&self, snippet_id: &str) -> Result<Vec<SnippetRevision>> {
460 let conn = self.read_conn().await;428 let conn = self.read_conn().await;
461 fetch_all(429 fetch_all(
@@ -525,7 +493,6 @@ mod tests {
525 "round trip {v:?}"493 "round trip {v:?}"
526 );494 );
527 }495 }
528- // The stored literals: changing one breaks saved snippets.
529 for (v, literal) in [496 for (v, literal) in [
530 (SnippetVisibility::Public, "public"),497 (SnippetVisibility::Public, "public"),
531 (SnippetVisibility::Unlisted, "unlisted"),498 (SnippetVisibility::Unlisted, "unlisted"),
@@ -578,7 +545,6 @@ mod tests {
578 assert_eq!(listed.len(), 1);545 assert_eq!(listed.len(), 1);
579 assert_eq!(listed[0].file_count, 1);546 assert_eq!(listed[0].file_count, 1);
580 547
581- // Only the owner can save.
582 let denied = store548 let denied = store
583 .update_snippet(549 .update_snippet(
584 &bob.id,550 &bob.id,
crates/forge-core/src/store/suggest.rsmodified+0 -10
@@ -1,5 +1,3 @@
1-//! Lookups behind the `@` and `#` autocomplete of the markdown editors.
2-
3 use turso::Value;1 use turso::Value;
4 2
5 use super::issues::like_pattern;3 use super::issues::like_pattern;
@@ -7,7 +5,6 @@ use super::{Store, col_int, col_text, fetch_all};
7 use crate::error::Result;5 use crate::error::Result;
8 use crate::names::normalize_name;6 use crate::names::normalize_name;
9 7
10-/// One `#` suggestion: an issue or pull request.
11 #[derive(Debug, Clone)]8 #[derive(Debug, Clone)]
12 pub struct IssueSuggestion {9 pub struct IssueSuggestion {
13 pub number: i64,10 pub number: i64,
@@ -17,9 +14,6 @@ pub struct IssueSuggestion {
17 }14 }
18 15
19 impl Store {16 impl Store {
20- /// Usernames starting with `prefix` (case-insensitive) that are people in the repo, nearest
21- /// first: the owner and collaborators, then anyone who opened an issue or commented, then
22- /// every other person account. At most `limit` names, no duplicates.
23 pub async fn suggest_usernames(17 pub async fn suggest_usernames(
24 &self,18 &self,
25 repo_id: &str,19 repo_id: &str,
@@ -31,7 +25,6 @@ impl Store {
31 p.remove(0);25 p.remove(0);
32 p26 p
33 };27 };
34- // `like_pattern` wraps in `%..%`; for a prefix match drop the leading one (done above).
35 let cap = Value::Integer(i64::try_from(limit).unwrap_or(8));28 let cap = Value::Integer(i64::try_from(limit).unwrap_or(8));
36 let conn = self.read_conn().await;29 let conn = self.read_conn().await;
37 fetch_all(30 fetch_all(
@@ -51,8 +44,6 @@ impl Store {
51 .await44 .await
52 }45 }
53 46
54- /// Issues and pull requests of the repo whose number starts with `q` (when it is digits) or
55- /// whose title contains it. Newest first, at most `limit`.
56 pub async fn suggest_issues(47 pub async fn suggest_issues(
57 &self,48 &self,
58 repo_id: &str,49 repo_id: &str,
@@ -120,7 +111,6 @@ mod tests {
120 .create_issue(&repo.id, &tahinli.id, "Docs", "")111 .create_issue(&repo.id, &tahinli.id, "Docs", "")
121 .await112 .await
122 .unwrap();113 .unwrap();
123- // Owner first, then participant, then the rest.
124 let names = store.suggest_usernames(&repo.id, "ta", 8).await.unwrap();114 let names = store.suggest_usernames(&repo.id, "ta", 8).await.unwrap();
125 assert_eq!(names, ["tahinli", "tanya", "tam"]);115 assert_eq!(names, ["tahinli", "tanya", "tam"]);
126 assert_eq!(116 assert_eq!(
crates/forge-core/src/store/suspension.rsmodified+0 -20
@@ -1,35 +1,25 @@
1-//! Account suspension and the admin-only account facts (migration 0055).
2-//!
3-//! A suspended user keeps their data but cannot sign in. The session, token and SSH key lookups
4-//! in `store/mod.rs` skip a suspended owner, so every transport stops at once.
5-
6 use turso::Connection;1 use turso::Connection;
7 2
8 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt};3 use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt};
9 use crate::error::{Error, Result};4 use crate::error::{Error, Result};
10 use crate::time::now_stamp;5 use crate::time::now_stamp;
11 6
12-/// Longest accepted suspension reason, in characters.
13 pub const MAX_REASON_CHARS: usize = 300;7 pub const MAX_REASON_CHARS: usize = 300;
14 8
15-/// Why and when an account was suspended.
16 #[derive(Debug, Clone, PartialEq, Eq)]9 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct Suspension {10 pub struct Suspension {
18 pub reason: String,11 pub reason: String,
19 pub suspended_at: String,12 pub suspended_at: String,
20 }13 }
21 14
22-/// Facts the admin user page shows.
23 #[derive(Debug, Clone, PartialEq, Eq)]15 #[derive(Debug, Clone, PartialEq, Eq)]
24 pub struct AccountFacts {16 pub struct AccountFacts {
25 pub repo_count: i64,17 pub repo_count: i64,
26- /// RFC 3339 stamp of the last successful sign-in in the audit log.
27 pub last_login: Option<String>,18 pub last_login: Option<String>,
28 pub two_factor: bool,19 pub two_factor: bool,
29 }20 }
30 21
31 impl Store {22 impl Store {
32- /// The suspension of `user_id`, if any.
33 pub async fn suspension(&self, user_id: &str) -> Result<Option<Suspension>> {23 pub async fn suspension(&self, user_id: &str) -> Result<Option<Suspension>> {
34 let conn = self.read_conn().await;24 let conn = self.read_conn().await;
35 fetch_opt(25 fetch_opt(
@@ -46,8 +36,6 @@ impl Store {
46 .await36 .await
47 }37 }
48 38
49- /// Suspends `user_id` and signs out every session. Refused for an organization and for the
50- /// last administrator who is not suspended.
51 pub async fn suspend_user(&self, user_id: &str, reason: &str, by: Option<&str>) -> Result<()> {39 pub async fn suspend_user(&self, user_id: &str, reason: &str, by: Option<&str>) -> Result<()> {
52 let reason = reason.trim();40 let reason = reason.trim();
53 if reason.chars().count() > MAX_REASON_CHARS || reason.chars().any(char::is_control) {41 if reason.chars().count() > MAX_REASON_CHARS || reason.chars().any(char::is_control) {
@@ -93,7 +81,6 @@ impl Store {
93 Ok(())81 Ok(())
94 }82 }
95 83
96- /// Lifts a suspension. Returns whether one existed.
97 pub async fn unsuspend_user(&self, user_id: &str) -> Result<bool> {84 pub async fn unsuspend_user(&self, user_id: &str) -> Result<bool> {
98 let conn = self.inner.conn.lock().await;85 let conn = self.inner.conn.lock().await;
99 let n = conn86 let n = conn
@@ -106,13 +93,11 @@ impl Store {
106 Ok(n > 0)93 Ok(n > 0)
107 }94 }
108 95
109- /// Administrators other than `user_id`: zero means `user_id` is the last one and cannot be demoted.
110 pub async fn other_admin_count(&self, user_id: &str) -> Result<i64> {96 pub async fn other_admin_count(&self, user_id: &str) -> Result<i64> {
111 let conn = self.read_conn().await;97 let conn = self.read_conn().await;
112 other_active_admins(&conn, user_id).await98 other_active_admins(&conn, user_id).await
113 }99 }
114 100
115- /// Grants or revokes the admin flag. Revoking is refused for the last administrator.
116 pub async fn set_admin(&self, user_id: &str, admin: bool) -> Result<()> {101 pub async fn set_admin(&self, user_id: &str, admin: bool) -> Result<()> {
117 let conn = self.inner.conn.lock().await;102 let conn = self.inner.conn.lock().await;
118 let uid = user_id.to_string();103 let uid = user_id.to_string();
@@ -145,7 +130,6 @@ impl Store {
145 Ok(())130 Ok(())
146 }131 }
147 132
148- /// Repo count, last sign-in and 2FA state for the admin user page.
149 pub async fn account_facts(&self, user_id: &str) -> Result<AccountFacts> {133 pub async fn account_facts(&self, user_id: &str) -> Result<AccountFacts> {
150 let conn = self.read_conn().await;134 let conn = self.read_conn().await;
151 let uid = user_id.to_string();135 let uid = user_id.to_string();
@@ -214,7 +198,6 @@ mod tests {
214 async fn suspension_scenarios() {198 async fn suspension_scenarios() {
215 let (store, admin, other, _d) = fixture().await;199 let (store, admin, other, _d) = fixture().await;
216 200
217- // Scenario: suspending ends the user's sessions until it is lifted.
218 store201 store
219 .create_session(&other.id, "th", "csrf", "2999-01-01T00:00:00Z", None, None)202 .create_session(&other.id, "th", "csrf", "2999-01-01T00:00:00Z", None, None)
220 .await203 .await
@@ -229,7 +212,6 @@ mod tests {
229 assert!(store.unsuspend_user(&other.id).await.unwrap());212 assert!(store.unsuspend_user(&other.id).await.unwrap());
230 assert!(store.suspension(&other.id).await.unwrap().is_none());213 assert!(store.suspension(&other.id).await.unwrap().is_none());
231 214
232- // Scenario: suspending also revokes API tokens and SSH keys until lifted.
233 store215 store
234 .create_token(&other.id, "ci", "tokhash", &["repo".to_owned()], None)216 .create_token(&other.id, "ci", "tokhash", &["repo".to_owned()], None)
235 .await217 .await
@@ -247,8 +229,6 @@ mod tests {
247 assert!(store.token_by_hash("tokhash").await.unwrap().is_some());229 assert!(store.token_by_hash("tokhash").await.unwrap().is_some());
248 assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_some());230 assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_some());
249 231
250- // Scenario: the last admin cannot be demoted or suspended.
251- // Runs last because it promotes `other` to admin.
252 assert!(matches!(232 assert!(matches!(
253 store.set_admin(&admin.id, false).await,233 store.set_admin(&admin.id, false).await,
254 Err(Error::Conflict(_))234 Err(Error::Conflict(_))
crates/forge-core/src/store/transfers.rsmodified+0 -39
@@ -1,11 +1,3 @@
1-//! Repo transfer acceptance. A transfer started by a repo owner waits in `repo_transfers` (migration
2-//! 0032) until its target accepts, declines, the initiator cancels, or it expires after 7 days. The
3-//! target is a person, or an org: any owner of the org may accept. Instance admins skip this and
4-//! call `Store::transfer_repo` directly.
5-//!
6-//! Only one transfer per repo is open at a time. A row whose target is already the owner is stale
7-//! and never listed.
8-
9 use turso::Row;1 use turso::Row;
10 2
11 use super::finish;3 use super::finish;
@@ -15,19 +7,15 @@ use crate::error::{Error, Result};
15 use crate::time::{now_stamp, stamp_after};7 use crate::time::{now_stamp, stamp_after};
16 use std::time::Duration;8 use std::time::Duration;
17 9
18-/// How long a pending transfer waits for its target.
19 pub const TRANSFER_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);10 pub const TRANSFER_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
20 11
21-/// An open transfer, with the names the pages show.
22 #[derive(Debug, Clone, PartialEq, Eq)]12 #[derive(Debug, Clone, PartialEq, Eq)]
23 pub struct PendingTransfer {13 pub struct PendingTransfer {
24 pub repo_id: String,14 pub repo_id: String,
25 pub repo_name: String,15 pub repo_name: String,
26- /// The owner the repo has now (the initiator's side).
27 pub from_owner_name: String,16 pub from_owner_name: String,
28 pub to_owner_id: String,17 pub to_owner_id: String,
29 pub to_owner_name: String,18 pub to_owner_name: String,
30- /// True when the target is an org; any owner of it may accept.
31 pub to_is_org: bool,19 pub to_is_org: bool,
32 pub initiated_by_id: String,20 pub initiated_by_id: String,
33 pub initiated_by_name: String,21 pub initiated_by_name: String,
@@ -35,8 +23,6 @@ pub struct PendingTransfer {
35 pub expires_at: String,23 pub expires_at: String,
36 }24 }
37 25
38-/// Transfer rows joined with the repo, its owner, the target and the initiator. The `WHERE`
39-/// clause is appended by each query. Parameter `?2` is always the current stamp.
40 const TRANSFER_SELECT: &str = "SELECT t.repo_id, r.name, f.username, t.to_owner_id, u.username, \26 const TRANSFER_SELECT: &str = "SELECT t.repo_id, r.name, f.username, t.to_owner_id, u.username, \
41 u.kind, t.initiated_by, i.username, t.created_at, t.expires_at FROM repo_transfers t \27 u.kind, t.initiated_by, i.username, t.created_at, t.expires_at FROM repo_transfers t \
42 JOIN repos r ON r.id = t.repo_id \28 JOIN repos r ON r.id = t.repo_id \
@@ -44,7 +30,6 @@ const TRANSFER_SELECT: &str = "SELECT t.repo_id, r.name, f.username, t.to_owner_
44 JOIN users u ON u.id = t.to_owner_id \30 JOIN users u ON u.id = t.to_owner_id \
45 JOIN users i ON i.id = t.initiated_by";31 JOIN users i ON i.id = t.initiated_by";
46 32
47-/// Open means unexpired and not already owned by the target.
48 const OPEN_FILTER: &str = "t.expires_at > ?2 AND t.to_owner_id != r.owner_id";33 const OPEN_FILTER: &str = "t.expires_at > ?2 AND t.to_owner_id != r.owner_id";
49 34
50 fn map_transfer(row: &Row) -> Result<PendingTransfer> {35 fn map_transfer(row: &Row) -> Result<PendingTransfer> {
@@ -63,7 +48,6 @@ fn map_transfer(row: &Row) -> Result<PendingTransfer> {
63 }48 }
64 49
65 impl Store {50 impl Store {
66- /// The open transfer of a repo, or `None`.
67 pub async fn pending_transfer(&self, repo_id: &str) -> Result<Option<PendingTransfer>> {51 pub async fn pending_transfer(&self, repo_id: &str) -> Result<Option<PendingTransfer>> {
68 let conn = self.read_conn().await;52 let conn = self.read_conn().await;
69 fetch_opt(53 fetch_opt(
@@ -75,8 +59,6 @@ impl Store {
75 .await59 .await
76 }60 }
77 61
78- /// The open transfers that `user_id` may accept: those whose target is the user, or an org
79- /// the user owns. Oldest first.
80 pub async fn pending_transfers_for_user(&self, user_id: &str) -> Result<Vec<PendingTransfer>> {62 pub async fn pending_transfers_for_user(&self, user_id: &str) -> Result<Vec<PendingTransfer>> {
81 let conn = self.read_conn().await;63 let conn = self.read_conn().await;
82 fetch_all(64 fetch_all(
@@ -92,8 +74,6 @@ impl Store {
92 .await74 .await
93 }75 }
94 76
95- /// Whether `user_id` may accept or decline `transfer`: the target person, or an owner of the
96- /// target org.
97 pub async fn can_accept_transfer(77 pub async fn can_accept_transfer(
98 &self,78 &self,
99 user_id: &str,79 user_id: &str,
@@ -106,9 +86,6 @@ impl Store {
106 == Some(OrgMemberRole::Owner))86 == Some(OrgMemberRole::Owner))
107 }87 }
108 88
109- /// Opens a transfer of `repo_id` to `to_owner_id`, started by `initiated_by`. The repo does not
110- /// move until the target accepts. Refused with `Conflict` when the repo already belongs to the
111- /// target, the target already has a repo of that name, or a transfer is already open.
112 pub async fn initiate_transfer(89 pub async fn initiate_transfer(
113 &self,90 &self,
114 repo_id: &str,91 repo_id: &str,
@@ -131,7 +108,6 @@ impl Store {
131 "the repository already belongs to that owner".into(),108 "the repository already belongs to that owner".into(),
132 ));109 ));
133 }110 }
134- // Expired or stale rows for this repo make way for the new one.
135 tx.execute(111 tx.execute(
136 "DELETE FROM repo_transfers WHERE repo_id = ?1 AND (expires_at <= ?2 OR to_owner_id = ?3)",112 "DELETE FROM repo_transfers WHERE repo_id = ?1 AND (expires_at <= ?2 OR to_owner_id = ?3)",
137 (repo_id.to_string(), now_stamp(), owner_id.clone()),113 (repo_id.to_string(), now_stamp(), owner_id.clone()),
@@ -187,23 +163,17 @@ impl Store {
187 finish(tx, outcome).await163 finish(tx, outcome).await
188 }164 }
189 165
190- /// Accepts the open transfer of `repo_id` as `user_id` and moves the repo. Someone who may not
191- /// accept, or a repo with no open transfer, gets `NotFound`. A name clash found now gives
192- /// `Conflict`, and the transfer stays open.
193 pub async fn accept_transfer(&self, repo_id: &str, user_id: &str) -> Result<()> {166 pub async fn accept_transfer(&self, repo_id: &str, user_id: &str) -> Result<()> {
194 let transfer = self.acceptable_transfer(repo_id, user_id).await?;167 let transfer = self.acceptable_transfer(repo_id, user_id).await?;
195 self.transfer_repo(repo_id, &transfer.to_owner_id).await?;168 self.transfer_repo(repo_id, &transfer.to_owner_id).await?;
196 self.delete_transfer_row(repo_id).await169 self.delete_transfer_row(repo_id).await
197 }170 }
198 171
199- /// Declines the open transfer of `repo_id` as `user_id`. The repo stays where it is.
200 pub async fn decline_transfer(&self, repo_id: &str, user_id: &str) -> Result<()> {172 pub async fn decline_transfer(&self, repo_id: &str, user_id: &str) -> Result<()> {
201 self.acceptable_transfer(repo_id, user_id).await?;173 self.acceptable_transfer(repo_id, user_id).await?;
202 self.delete_transfer_row(repo_id).await174 self.delete_transfer_row(repo_id).await
203 }175 }
204 176
205- /// Cancels the open transfer of `repo_id`. The web layer checks that the caller is the
206- /// initiator or may delete the repo. `NotFound` when nothing is open.
207 pub async fn cancel_transfer(&self, repo_id: &str) -> Result<()> {177 pub async fn cancel_transfer(&self, repo_id: &str) -> Result<()> {
208 self.pending_transfer(repo_id)178 self.pending_transfer(repo_id)
209 .await?179 .await?
@@ -211,7 +181,6 @@ impl Store {
211 self.delete_transfer_row(repo_id).await181 self.delete_transfer_row(repo_id).await
212 }182 }
213 183
214- /// The open transfer of `repo_id` when `user_id` may act on it, else `NotFound`.
215 async fn acceptable_transfer(&self, repo_id: &str, user_id: &str) -> Result<PendingTransfer> {184 async fn acceptable_transfer(&self, repo_id: &str, user_id: &str) -> Result<PendingTransfer> {
216 let transfer = self185 let transfer = self
217 .pending_transfer(repo_id)186 .pending_transfer(repo_id)
@@ -279,7 +248,6 @@ mod tests {
279 store.repo_by_id(repo_id).await.unwrap().unwrap().owner_id248 store.repo_by_id(repo_id).await.unwrap().unwrap().owner_id
280 }249 }
281 250
282- /// A fresh repo owned by tahinli, so each scenario has its own transfer state.
283 async fn new_repo(fx: &Fixture, name: &str) -> String {251 async fn new_repo(fx: &Fixture, name: &str) -> String {
284 fx.store252 fx.store
285 .create_repo(&fx.tahinli.id, name, "", Visibility::Private, "main")253 .create_repo(&fx.tahinli.id, name, "", Visibility::Private, "main")
@@ -292,7 +260,6 @@ mod tests {
292 async fn transfer_scenarios() {260 async fn transfer_scenarios() {
293 let fx = fixture().await;261 let fx = fixture().await;
294 262
295- // Scenario: an org target is visible to its owners only and accepted by them.
296 let repo = new_repo(&fx, "for-acme").await;263 let repo = new_repo(&fx, "for-acme").await;
297 let org = fx.store.create_org("acme", &fx.carol.id).await.unwrap();264 let org = fx.store.create_org("acme", &fx.carol.id).await.unwrap();
298 assert_eq!(org.kind, AccountKind::Org);265 assert_eq!(org.kind, AccountKind::Org);
@@ -329,7 +296,6 @@ mod tests {
329 fx.store.accept_transfer(&repo, &fx.carol.id).await.unwrap();296 fx.store.accept_transfer(&repo, &fx.carol.id).await.unwrap();
330 assert_eq!(owner_of(&fx.store, &repo).await, org.id);297 assert_eq!(owner_of(&fx.store, &repo).await, org.id);
331 298
332- // Scenario: the repo stays with its owner until the target accepts.
333 let repo = fx.repo.id.clone();299 let repo = fx.repo.id.clone();
334 fx.store300 fx.store
335 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)301 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)
@@ -346,7 +312,6 @@ mod tests {
346 assert_eq!(owner_of(&fx.store, &repo).await, fx.bob.id);312 assert_eq!(owner_of(&fx.store, &repo).await, fx.bob.id);
347 assert!(fx.store.pending_transfer(&repo).await.unwrap().is_none());313 assert!(fx.store.pending_transfer(&repo).await.unwrap().is_none());
348 314
349- // Scenario: only the target can accept; the owner and strangers get NotFound.
350 let repo = new_repo(&fx, "targeted").await;315 let repo = new_repo(&fx, "targeted").await;
351 fx.store316 fx.store
352 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)317 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)
@@ -358,7 +323,6 @@ mod tests {
358 assert!(matches!(err, Err(Error::NotFound)));323 assert!(matches!(err, Err(Error::NotFound)));
359 assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id);324 assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id);
360 325
361- // Scenario: a declined transfer and a cancelled one both leave the repo in place.
362 let repo = new_repo(&fx, "declined").await;326 let repo = new_repo(&fx, "declined").await;
363 fx.store327 fx.store
364 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)328 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)
@@ -380,7 +344,6 @@ mod tests {
380 ));344 ));
381 assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id);345 assert_eq!(owner_of(&fx.store, &repo).await, fx.tahinli.id);
382 346
383- // Scenario: a second open transfer on the same repo conflicts.
384 let repo = new_repo(&fx, "contested").await;347 let repo = new_repo(&fx, "contested").await;
385 fx.store348 fx.store
386 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)349 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)
@@ -392,7 +355,6 @@ mod tests {
392 .await;355 .await;
393 assert!(matches!(again, Err(Error::Conflict(_))));356 assert!(matches!(again, Err(Error::Conflict(_))));
394 357
395- // Scenario: an expired transfer cannot be accepted and is replaced by a new one.
396 let repo = new_repo(&fx, "expiring").await;358 let repo = new_repo(&fx, "expiring").await;
397 fx.store359 fx.store
398 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)360 .initiate_transfer(&repo, &fx.bob.id, &fx.tahinli.id)
@@ -421,7 +383,6 @@ mod tests {
421 let pending = fx.store.pending_transfer(&repo).await.unwrap().unwrap();383 let pending = fx.store.pending_transfer(&repo).await.unwrap().unwrap();
422 assert_eq!(pending.to_owner_name, "carol");384 assert_eq!(pending.to_owner_name, "carol");
423 385
424- // Scenario: a target that already has a repo of the same name is refused up front.
425 let repo = new_repo(&fx, "clash").await;386 let repo = new_repo(&fx, "clash").await;
426 fx.store387 fx.store
427 .create_repo(&fx.bob.id, "clash", "", Visibility::Private, "main")388 .create_repo(&fx.bob.id, "clash", "", Visibility::Private, "main")
crates/forge-core/src/store/ui_prefs.rsmodified+0 -37
@@ -1,41 +1,24 @@
1-//! Per-user UI preferences: the colour theme, the language, the colour choices and the side of the
2-//! shell sidebar. The colours are an accent and a base (neutral background, surface and text) for
3-//! each of the light and the dark theme. All are stored as text in `users` (migrations 0030, 0041,
4-//! 0042 and 0043). The web layer decides which values it offers; the store only checks that a
5-//! value is well formed, so a new language, accent or base needs no store change.
6-
7 use turso::IntoParams;1 use turso::IntoParams;
8 2
9 use super::{Store, db_err};3 use super::{Store, db_err};
10 use crate::error::{Error, Result};4 use crate::error::{Error, Result};
11 5
12-/// Accepted theme values, in the order the settings page lists them.
13 pub const THEMES: &[&str] = &["auto", "light", "dark"];6 pub const THEMES: &[&str] = &["auto", "light", "dark"];
14 7
15-/// The value meaning "follow the default", for both theme and language.
16 pub const AUTO: &str = "auto";8 pub const AUTO: &str = "auto";
17 9
18-/// The accent colour a new user gets. It must match the default palette in forge-web's
19-/// `accent_palette.rs`, which a test there checks.
20 pub const DEFAULT_ACCENT: &str = "sage";10 pub const DEFAULT_ACCENT: &str = "sage";
21 11
22-/// The base colour set a new user gets, for both themes. It must match the default base in
23-/// forge-web's `accent_palette.rs`, which a test there checks.
24 pub const DEFAULT_BASE: &str = "ink";12 pub const DEFAULT_BASE: &str = "ink";
25 13
26-/// The sidebar sides, in the order the settings page lists them.
27 pub const SIDEBAR_SIDES: &[&str] = &["left", "right"];14 pub const SIDEBAR_SIDES: &[&str] = &["left", "right"];
28 15
29-/// The side a new user's sidebar sits on. It is the side the shell has always used.
30 pub const DEFAULT_SIDEBAR: &str = "left";16 pub const DEFAULT_SIDEBAR: &str = "left";
31 17
32-/// Longest accepted language code, in bytes.
33 const MAX_LANGUAGE_LEN: usize = 16;18 const MAX_LANGUAGE_LEN: usize = 16;
34 19
35-/// Longest accepted accent id, in bytes.
36 const MAX_ACCENT_LEN: usize = 24;20 const MAX_ACCENT_LEN: usize = 24;
37 21
38-/// True for `auto` or a BCP 47 style tag such as `en`, `tr` or `pt-BR`.
39 pub fn valid_language(code: &str) -> bool {22 pub fn valid_language(code: &str) -> bool {
40 if code == AUTO {23 if code == AUTO {
41 return true;24 return true;
@@ -51,8 +34,6 @@ pub fn valid_language(code: &str) -> bool {
51 && parts.all(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric()))34 && parts.all(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric()))
52 }35 }
53 36
54-/// True for a short lowercase slug such as `sage` or `rose-2`: 1 to 24 ASCII letters, digits or
55-/// hyphens. Whether forge offers the id is the web layer's call.
56 pub fn valid_slug(id: &str) -> bool {37 pub fn valid_slug(id: &str) -> bool {
57 (1..=MAX_ACCENT_LEN).contains(&id.len())38 (1..=MAX_ACCENT_LEN).contains(&id.len())
58 && id39 && id
@@ -60,7 +41,6 @@ pub fn valid_slug(id: &str) -> bool {
60 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')41 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
61 }42 }
62 43
63-/// True for `left` or `right`, the two sides the sidebar can sit on.
64 pub fn valid_sidebar(side: &str) -> bool {44 pub fn valid_sidebar(side: &str) -> bool {
65 SIDEBAR_SIDES.contains(&side)45 SIDEBAR_SIDES.contains(&side)
66 }46 }
@@ -75,7 +55,6 @@ impl Store {
75 Ok(())55 Ok(())
76 }56 }
77 57
78- /// Sets the user's theme and language. Anything malformed is rejected and nothing is written.
79 pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> {58 pub async fn set_ui_prefs(&self, user_id: &str, theme: &str, language: &str) -> Result<()> {
80 if !THEMES.contains(&theme) {59 if !THEMES.contains(&theme) {
81 return Err(Error::Invalid(format!("theme {theme:?}")));60 return Err(Error::Invalid(format!("theme {theme:?}")));
@@ -90,8 +69,6 @@ impl Store {
90 .await69 .await
91 }70 }
92 71
93- /// Sets the user's accent colour id for both themes. A malformed id is rejected and nothing is
94- /// written.
95 pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> {72 pub async fn set_accent(&self, user_id: &str, accent: &str) -> Result<()> {
96 if !valid_slug(accent) {73 if !valid_slug(accent) {
97 return Err(Error::Invalid(format!("accent {accent:?}")));74 return Err(Error::Invalid(format!("accent {accent:?}")));
@@ -103,8 +80,6 @@ impl Store {
103 .await80 .await
104 }81 }
105 82
106- /// Sets the four colour choices: the accent and the base for the light theme, then the accent
107- /// and the base for the dark theme. If any id is malformed, nothing is written.
108 pub async fn set_colours(83 pub async fn set_colours(
109 &self,84 &self,
110 user_id: &str,85 user_id: &str,
@@ -137,8 +112,6 @@ impl Store {
137 .await112 .await
138 }113 }
139 114
140- /// Sets the side the shell sidebar sits on. Anything but `left` or `right` is rejected and
141- /// nothing is written.
142 pub async fn set_sidebar_side(&self, user_id: &str, side: &str) -> Result<()> {115 pub async fn set_sidebar_side(&self, user_id: &str, side: &str) -> Result<()> {
143 if !valid_sidebar(side) {116 if !valid_sidebar(side) {
144 return Err(Error::Invalid(format!("sidebar {side:?}")));117 return Err(Error::Invalid(format!("sidebar {side:?}")));
@@ -157,7 +130,6 @@ mod tests {
157 130
158 #[test]131 #[test]
159 fn validators_accept_and_reject_their_inputs() {132 fn validators_accept_and_reject_their_inputs() {
160- // Language codes.
161 for ok in ["auto", "en", "tr", "pt-BR", "zh-Hant-TW"] {133 for ok in ["auto", "en", "tr", "pt-BR", "zh-Hant-TW"] {
162 assert!(valid_language(ok), "case language {ok}");134 assert!(valid_language(ok), "case language {ok}");
163 }135 }
@@ -171,7 +143,6 @@ mod tests {
171 "case language too long"143 "case language too long"
172 );144 );
173 145
174- // Accent ids.
175 let longest = "a".repeat(MAX_ACCENT_LEN);146 let longest = "a".repeat(MAX_ACCENT_LEN);
176 let too_long = "a".repeat(MAX_ACCENT_LEN + 1);147 let too_long = "a".repeat(MAX_ACCENT_LEN + 1);
177 for ok in ["sage", "rose-2", "a", longest.as_str()] {148 for ok in ["sage", "rose-2", "a", longest.as_str()] {
@@ -181,7 +152,6 @@ mod tests {
181 assert!(!valid_slug(bad), "case accent {bad}");152 assert!(!valid_slug(bad), "case accent {bad}");
182 }153 }
183 154
184- // Sidebar sides.
185 assert!(valid_sidebar("left"), "case sidebar left");155 assert!(valid_sidebar("left"), "case sidebar left");
186 assert!(valid_sidebar("right"), "case sidebar right");156 assert!(valid_sidebar("right"), "case sidebar right");
187 for bad in ["", "center", "Left", "right-2"] {157 for bad in ["", "center", "Left", "right-2"] {
@@ -189,13 +159,11 @@ mod tests {
189 }159 }
190 }160 }
191 161
192- /// Each case gets its own user on one shared store, so defaults are fresh.
193 #[tokio::test]162 #[tokio::test]
194 async fn preference_setters_persist_valid_values_and_refuse_bad_ones() {163 async fn preference_setters_persist_valid_values_and_refuse_bad_ones() {
195 let dir = tempfile::tempdir().unwrap();164 let dir = tempfile::tempdir().unwrap();
196 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();165 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
197 166
198- // Case accent: a single accent persists, bad values change nothing.
199 let user = store167 let user = store
200 .create_user("accent_case", None, "hash", false)168 .create_user("accent_case", None, "hash", false)
201 .await169 .await
@@ -221,7 +189,6 @@ mod tests {
221 "case accent unchanged"189 "case accent unchanged"
222 );190 );
223 191
224- // Case colours: the four colours persist, bad values change nothing.
225 let user = store192 let user = store
226 .create_user("colours_case", None, "hash", false)193 .create_user("colours_case", None, "hash", false)
227 .await194 .await
@@ -277,7 +244,6 @@ mod tests {
277 "case colours unchanged"244 "case colours unchanged"
278 );245 );
279 246
280- // Case newer colours: newer accents and backgrounds persist.
281 let user = store247 let user = store
282 .create_user("newer_case", None, "hash", false)248 .create_user("newer_case", None, "hash", false)
283 .await249 .await
@@ -319,7 +285,6 @@ mod tests {
319 assert_eq!(still.accent, "clay", "case newer colours unchanged");285 assert_eq!(still.accent, "clay", "case newer colours unchanged");
320 assert_eq!(still.base_light, "dusk", "case newer colours unchanged");286 assert_eq!(still.base_light, "dusk", "case newer colours unchanged");
321 287
322- // Case set accent: sets both accents and keeps the bases.
323 let user = store288 let user = store
324 .create_user("set_accent_case", None, "hash", false)289 .create_user("set_accent_case", None, "hash", false)
325 .await290 .await
@@ -335,7 +300,6 @@ mod tests {
335 assert_eq!(stored.base_light, "dusk", "case set accent bases kept");300 assert_eq!(stored.base_light, "dusk", "case set accent bases kept");
336 assert_eq!(stored.base_dark, "ink", "case set accent bases kept");301 assert_eq!(stored.base_dark, "ink", "case set accent bases kept");
337 302
338- // Case theme and language: persist, bad values change nothing.
339 let user = store303 let user = store
340 .create_user("prefs_case", None, "hash", false)304 .create_user("prefs_case", None, "hash", false)
341 .await305 .await
@@ -364,7 +328,6 @@ mod tests {
364 "case prefs unchanged"328 "case prefs unchanged"
365 );329 );
366 330
367- // Case sidebar: persists, bad values change nothing.
368 let user = store331 let user = store
369 .create_user("sidebar_case", None, "hash", false)332 .create_user("sidebar_case", None, "hash", false)
370 .await333 .await
crates/forge-core/src/store/user_delete.rsmodified+0 -33
@@ -1,8 +1,3 @@
1-//! Account deletion. Everything the user authored or acted on moves to the reserved `ghost`
2-//! user, so issues, comments and reviews keep their text and their place in the history. Rows
3-//! that only make sense for the account (sessions, keys, tokens, stars, ...) are removed. The
4-//! whole deletion is one transaction: it either applies completely or changes nothing.
5-
6 use turso::Connection;1 use turso::Connection;
7 use turso::transaction::Transaction;2 use turso::transaction::Transaction;
8 3
@@ -12,41 +7,29 @@ use crate::error::{Error, Result};
12 use crate::model::User;7 use crate::model::User;
13 use crate::time::now_stamp;8 use crate::time::now_stamp;
14 9
15-/// Login name of the reserved ghost account. `names::RESERVED` contains it, so nobody can
16-/// register it.
17 pub const GHOST_USERNAME: &str = "ghost";10 pub const GHOST_USERNAME: &str = "ghost";
18 11
19-/// Stored instead of a password hash. It is not a PHC string, so `password::verify_password`
20-/// is always false and the ghost account cannot sign in.
21 const GHOST_PASSWORD_HASH: &str = "!";12 const GHOST_PASSWORD_HASH: &str = "!";
22 13
23-/// Refusal text when the user is the last owner of an organization. Shown on the admin page and
24-/// by the admin CLI.
25 pub const LAST_ORG_OWNER: &str =14 pub const LAST_ORG_OWNER: &str =
26 "this user is the last owner of an organization: make another member an owner first";15 "this user is the last owner of an organization: make another member an owner first";
27 16
28-/// Orgs where `?1` is the only owner. A non-zero count refuses the deletion.
29 const LAST_OWNER_OF_ORG: &str = "SELECT COUNT(*) FROM org_members AS mine \17 const LAST_OWNER_OF_ORG: &str = "SELECT COUNT(*) FROM org_members AS mine \
30 WHERE mine.user_id = ?1 AND mine.role = 'owner' AND NOT EXISTS (\18 WHERE mine.user_id = ?1 AND mine.role = 'owner' AND NOT EXISTS (\
31 SELECT 1 FROM org_members AS other WHERE other.org_id = mine.org_id \19 SELECT 1 FROM org_members AS other WHERE other.org_id = mine.org_id \
32 AND other.role = 'owner' AND other.user_id <> ?1)";20 AND other.role = 'owner' AND other.user_id <> ?1)";
33 21
34-/// Unpublished review drafts of the user. `?1` is the user id.
35 const DRAFT_REVIEWS: &str =22 const DRAFT_REVIEWS: &str =
36 "SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending'";23 "SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending'";
37-/// Comments inside those drafts. `?1` is the user id.
38 const DRAFT_COMMENTS: &str = "SELECT id FROM review_comments WHERE review_id IN (\24 const DRAFT_COMMENTS: &str = "SELECT id FROM review_comments WHERE review_id IN (\
39 SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending')";25 SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending')";
40 26
41-/// Filters that keep drafts out of the reassignment (drafts are deleted, not moved).
42 const NOT_DRAFT_REVIEW: &str = " AND state <> 'pending'";27 const NOT_DRAFT_REVIEW: &str = " AND state <> 'pending'";
43 const NOT_IN_DRAFT: &str = " AND review_id NOT IN (SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending')";28 const NOT_IN_DRAFT: &str = " AND review_id NOT IN (SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending')";
44 const NOT_DRAFT_EDIT: &str = " AND NOT (target_kind = 'review_comment' AND target_id IN (\29 const NOT_DRAFT_EDIT: &str = " AND NOT (target_kind = 'review_comment' AND target_id IN (\
45 SELECT id FROM review_comments WHERE review_id IN (\30 SELECT id FROM review_comments WHERE review_id IN (\
46 SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending')))";31 SELECT id FROM pull_reviews WHERE author_id = ?1 AND state = 'pending')))";
47 32
48-/// Rows that move to the ghost user: `(label, table, column, extra filter)`. The filter is
49-/// appended to the `WHERE column = ?1` clause.
50 const REASSIGNED: &[(&str, &str, &str, &str)] = &[33 const REASSIGNED: &[(&str, &str, &str, &str)] = &[
51 ("issues", "issues", "author_id", ""),34 ("issues", "issues", "author_id", ""),
52 ("attachments", "attachments", "uploader_id", ""),35 ("attachments", "attachments", "uploader_id", ""),
@@ -109,8 +92,6 @@ const REASSIGNED: &[(&str, &str, &str, &str)] = &[
109 ),92 ),
110 ];93 ];
111 94
112-/// Rows that belong to the account and are deleted with it: `(label, table, column)`. Drafts are
113-/// listed separately.
114 const REMOVED: &[(&str, &str, &str)] = &[95 const REMOVED: &[(&str, &str, &str)] = &[
115 ("sessions", "sessions", "user_id"),96 ("sessions", "sessions", "user_id"),
116 ("SSH keys", "ssh_keys", "user_id"),97 ("SSH keys", "ssh_keys", "user_id"),
@@ -143,17 +124,13 @@ const REMOVED: &[(&str, &str, &str)] = &[
143 ("review requests", "review_requests", "reviewer_id"),124 ("review requests", "review_requests", "reviewer_id"),
144 ];125 ];
145 126
146-/// What a deletion did, or would do: row counts per kind, in the order the lists above give.
147 #[derive(Debug, Clone, Default, PartialEq, Eq)]127 #[derive(Debug, Clone, Default, PartialEq, Eq)]
148 pub struct DeletionReport {128 pub struct DeletionReport {
149- /// Rows moved to the ghost user.
150 pub reassigned: Vec<(&'static str, u64)>,129 pub reassigned: Vec<(&'static str, u64)>,
151- /// Rows removed with the account, including unpublished review drafts.
152 pub removed: Vec<(&'static str, u64)>,130 pub removed: Vec<(&'static str, u64)>,
153 }131 }
154 132
155 impl Store {133 impl Store {
156- /// Returns the reserved ghost account, creating it on first use. Safe to call repeatedly.
157 pub async fn ensure_ghost_user(&self) -> Result<User> {134 pub async fn ensure_ghost_user(&self) -> Result<User> {
158 let conn = self.inner.conn.lock().await;135 let conn = self.inner.conn.lock().await;
159 let existing = fetch_opt(136 let existing = fetch_opt(
@@ -190,9 +167,6 @@ impl Store {
190 .ok_or_else(missing)167 .ok_or_else(missing)
191 }168 }
192 169
193- /// Checks whether `user_id` can be deleted and reports what would happen. Changes nothing.
194- /// `ghost_id` is `None` when the ghost account does not exist yet, so a preview never
195- /// creates it.
196 pub async fn deletion_preview(170 pub async fn deletion_preview(
197 &self,171 &self,
198 user_id: &str,172 user_id: &str,
@@ -202,9 +176,6 @@ impl Store {
202 plan(&conn, user_id, ghost_id).await176 plan(&conn, user_id, ghost_id).await
203 }177 }
204 178
205- /// Deletes the account `user_id` in one transaction and moves its authored content to
206- /// `ghost_id`. Refused (and nothing changes) when the user owns repositories, is the last
207- /// administrator, or is the ghost account itself.
208 pub async fn delete_user(&self, user_id: &str, ghost_id: &str) -> Result<DeletionReport> {179 pub async fn delete_user(&self, user_id: &str, ghost_id: &str) -> Result<DeletionReport> {
209 let conn = self.inner.conn.lock().await;180 let conn = self.inner.conn.lock().await;
210 let tx = conn.unchecked_transaction().await.map_err(db_err)?;181 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -218,7 +189,6 @@ impl Store {
218 }189 }
219 }190 }
220 191
221-/// Refusal checks and row counts. Read-only, so it runs on the connection or a transaction.
222 async fn plan(conn: &Connection, user_id: &str, ghost_id: Option<&str>) -> Result<DeletionReport> {192 async fn plan(conn: &Connection, user_id: &str, ghost_id: Option<&str>) -> Result<DeletionReport> {
223 if ghost_id == Some(user_id) {193 if ghost_id == Some(user_id) {
224 return Err(Error::Forbidden(194 return Err(Error::Forbidden(
@@ -301,7 +271,6 @@ async fn plan(conn: &Connection, user_id: &str, ghost_id: Option<&str>) -> Resul
301 Ok(report)271 Ok(report)
302 }272 }
303 273
304-/// The writes. Callers run this inside the transaction that `plan` has already checked.
305 async fn apply(tx: &Transaction<'_>, user_id: &str, ghost_id: &str) -> Result<()> {274 async fn apply(tx: &Transaction<'_>, user_id: &str, ghost_id: &str) -> Result<()> {
306 let uid = user_id.to_string();275 let uid = user_id.to_string();
307 let gid = ghost_id.to_string();276 let gid = ghost_id.to_string();
@@ -367,7 +336,6 @@ mod tests {
367 _dir: tempfile::TempDir,336 _dir: tempfile::TempDir,
368 store: Store,337 store: Store,
369 ghost: User,338 ghost: User,
370- /// The only administrator; deleting it is refused.
371 admin: User,339 admin: User,
372 tahinli: User,340 tahinli: User,
373 bob: User,341 bob: User,
@@ -399,7 +367,6 @@ mod tests {
399 }367 }
400 }368 }
401 369
402- /// One integer from a query with a single `?1` text parameter.
403 async fn scalar(store: &Store, sql: &str, param: &str) -> i64 {370 async fn scalar(store: &Store, sql: &str, param: &str) -> i64 {
404 let conn = store.inner.conn.lock().await;371 let conn = store.inner.conn.lock().await;
405 fetch_opt(&conn, sql, (param.to_string(),), |row| col_int(row, 0))372 fetch_opt(&conn, sql, (param.to_string(),), |row| col_int(row, 0))
crates/forge-core/src/store/user_prefs.rsmodified+0 -9
@@ -1,20 +1,13 @@
1-//! Account preferences that are not columns of `users`: one text value per user and key, in
2-//! `user_prefs` (migration 0069). The web layer decides which keys exist and what each value may
3-//! be; this store only keeps the rows. Rows go with the user (ON DELETE CASCADE).
4-
5 use std::collections::HashMap;1 use std::collections::HashMap;
6 2
7 use super::{Store, col_text, db_err, fetch_all};3 use super::{Store, col_text, db_err, fetch_all};
8 use crate::error::Result;4 use crate::error::Result;
9 use crate::time::now_stamp;5 use crate::time::now_stamp;
10 6
11-/// Key of the run-finished tone: `on` or `off` (the default, no row).
12 pub const SOUND: &str = "sound";7 pub const SOUND: &str = "sound";
13-/// The sound values a user may store.
14 pub const SOUND_VALUES: &[&str] = &["on", "off"];8 pub const SOUND_VALUES: &[&str] = &["on", "off"];
15 9
16 impl Store {10 impl Store {
17- /// All of a user's preferences as `key -> value`.
18 pub async fn user_prefs(&self, user_id: &str) -> Result<HashMap<String, String>> {11 pub async fn user_prefs(&self, user_id: &str) -> Result<HashMap<String, String>> {
19 let conn = self.read_conn().await;12 let conn = self.read_conn().await;
20 let rows = fetch_all(13 let rows = fetch_all(
@@ -27,7 +20,6 @@ impl Store {
27 Ok(rows.into_iter().collect())20 Ok(rows.into_iter().collect())
28 }21 }
29 22
30- /// Stores `value` under `key` for the user, replacing an earlier value.
31 pub async fn set_user_pref(&self, user_id: &str, key: &str, value: &str) -> Result<()> {23 pub async fn set_user_pref(&self, user_id: &str, key: &str, value: &str) -> Result<()> {
32 let conn = self.inner.conn.lock().await;24 let conn = self.inner.conn.lock().await;
33 conn.execute(25 conn.execute(
@@ -46,7 +38,6 @@ impl Store {
46 Ok(())38 Ok(())
47 }39 }
48 40
49- /// Removes one preference. A key the user never set is not an error.
50 pub async fn delete_user_pref(&self, user_id: &str, key: &str) -> Result<()> {41 pub async fn delete_user_pref(&self, user_id: &str, key: &str) -> Result<()> {
51 let conn = self.inner.conn.lock().await;42 let conn = self.inner.conn.lock().await;
52 conn.execute(43 conn.execute(
crates/forge-core/src/store/web_push.rsmodified+0 -23
@@ -1,26 +1,16 @@
1-//! Web Push (migration 0063): the instance's VAPID key pair and each user's push subscriptions.
2-//! The store keeps the private key sealed; the web crate seals and opens it with the instance key.
3-
4 use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};1 use super::{Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
5 use crate::error::{Error, Result};2 use crate::error::{Error, Result};
6 use crate::time::now_stamp;3 use crate::time::now_stamp;
7 4
8-/// Most devices one account may hold. A subscription past this is refused, so a client cannot
9-/// grow the table without bound.
10 pub const MAX_DEVICES: i64 = 20;5 pub const MAX_DEVICES: i64 = 20;
11 6
12-/// One browser or installed app that receives pushes for `user_id`.
13 #[derive(Debug, Clone, PartialEq, Eq)]7 #[derive(Debug, Clone, PartialEq, Eq)]
14 pub struct PushSubscription {8 pub struct PushSubscription {
15 pub id: String,9 pub id: String,
16 pub user_id: String,10 pub user_id: String,
17- /// The push service URL. Unique across accounts.
18 pub endpoint: String,11 pub endpoint: String,
19- /// The browser's public key, base64url.
20 pub p256dh: String,12 pub p256dh: String,
21- /// The browser's auth secret, base64url.
22 pub auth: String,13 pub auth: String,
23- /// A short device label such as "Chrome on Android", derived from the User-Agent.
24 pub agent_label: String,14 pub agent_label: String,
25 pub created_at: String,15 pub created_at: String,
26 pub last_success_at: Option<String>,16 pub last_success_at: Option<String>,
@@ -42,8 +32,6 @@ fn map_row(row: &turso::Row) -> Result<PushSubscription> {
42 }32 }
43 33
44 impl Store {34 impl Store {
45- /// The instance's VAPID key pair as `(public key, sealed private key)`, or `None` before the
46- /// first one is generated.
47 pub async fn web_push_keys(&self) -> Result<Option<(String, String)>> {35 pub async fn web_push_keys(&self) -> Result<Option<(String, String)>> {
48 let conn = self.read_conn().await;36 let conn = self.read_conn().await;
49 fetch_opt(37 fetch_opt(
@@ -55,8 +43,6 @@ impl Store {
55 .await43 .await
56 }44 }
57 45
58- /// Stores the VAPID key pair unless one is already stored, and returns the stored pair. Two
59- /// requests that race to create the first key both end up with the same one.
60 pub async fn save_web_push_keys(46 pub async fn save_web_push_keys(
61 &self,47 &self,
62 public_key: &str,48 public_key: &str,
@@ -84,7 +70,6 @@ impl Store {
84 .ok_or_else(|| Error::Database("the VAPID key was not stored".into()))70 .ok_or_else(|| Error::Database("the VAPID key was not stored".into()))
85 }71 }
86 72
87- /// The devices of `user_id`, oldest first.
88 pub async fn push_subscriptions(&self, user_id: &str) -> Result<Vec<PushSubscription>> {73 pub async fn push_subscriptions(&self, user_id: &str) -> Result<Vec<PushSubscription>> {
89 let conn = self.read_conn().await;74 let conn = self.read_conn().await;
90 fetch_all(75 fetch_all(
@@ -98,9 +83,6 @@ impl Store {
98 .await83 .await
99 }84 }
100 85
101- /// Adds a device for `user_id`, or refreshes the keys of the device with this endpoint. The
102- /// endpoint moves to `user_id` when another account held it. Refused past `MAX_DEVICES` for
103- /// a new endpoint.
104 pub async fn save_push_subscription(86 pub async fn save_push_subscription(
105 &self,87 &self,
106 user_id: &str,88 user_id: &str,
@@ -151,7 +133,6 @@ impl Store {
151 .ok_or_else(|| Error::Database("the push subscription was not stored".into()))133 .ok_or_else(|| Error::Database("the push subscription was not stored".into()))
152 }134 }
153 135
154- /// Removes the device with this id when it belongs to `user_id`.
155 pub async fn delete_push_subscription(&self, user_id: &str, id: &str) -> Result<bool> {136 pub async fn delete_push_subscription(&self, user_id: &str, id: &str) -> Result<bool> {
156 let conn = self.inner.conn.lock().await;137 let conn = self.inner.conn.lock().await;
157 let n = conn138 let n = conn
@@ -164,7 +145,6 @@ impl Store {
164 Ok(n > 0)145 Ok(n > 0)
165 }146 }
166 147
167- /// Removes the device with this endpoint when it belongs to `user_id`.
168 pub async fn delete_push_subscription_by_endpoint(148 pub async fn delete_push_subscription_by_endpoint(
169 &self,149 &self,
170 user_id: &str,150 user_id: &str,
@@ -181,8 +161,6 @@ impl Store {
181 Ok(n > 0)161 Ok(n > 0)
182 }162 }
183 163
184- /// Removes the device with this endpoint whoever owns it. Used when the push service says
185- /// the subscription is gone (404 or 410).
186 pub async fn delete_push_endpoint(&self, endpoint: &str) -> Result<bool> {164 pub async fn delete_push_endpoint(&self, endpoint: &str) -> Result<bool> {
187 let conn = self.inner.conn.lock().await;165 let conn = self.inner.conn.lock().await;
188 let n = conn166 let n = conn
@@ -195,7 +173,6 @@ impl Store {
195 Ok(n > 0)173 Ok(n > 0)
196 }174 }
197 175
198- /// Records a delivery the push service accepted.
199 pub async fn mark_push_delivered(&self, id: &str) -> Result<()> {176 pub async fn mark_push_delivered(&self, id: &str) -> Result<()> {
200 let conn = self.inner.conn.lock().await;177 let conn = self.inner.conn.lock().await;
201 conn.execute(178 conn.execute(
crates/forge-core/src/store/webhooks.rsmodified+0 -70
@@ -1,9 +1,3 @@
1-//! Webhook storage: hooks, their sealed secrets, and the delivery queue.
2-//!
3-//! Sealing is the caller's job, as it is for TOTP: the caller runs `secret::seal` with the
4-//! instance key and passes the bytes in. `webhook_secret` takes the key and opens the value.
5-//! Timestamps are RFC 3339 UTC stamps, so `next_attempt_at <= now` is a text comparison.
6-
7 use std::time::Duration;1 use std::time::Duration;
8 2
9 use turso::{Connection, Row, Value};3 use turso::{Connection, Row, Value};
@@ -19,10 +13,7 @@ use crate::webhooks::{
19 AttemptOutcome, Delivery, DeliveryState, MAX_RESPONSE_BODY_BYTES, Webhook, WebhookEvent,13 AttemptOutcome, Delivery, DeliveryState, MAX_RESPONSE_BODY_BYTES, Webhook, WebhookEvent,
20 };14 };
21 15
22-/// How long a claimed delivery is held before it becomes due again. A crash mid-attempt
23-/// therefore retries after this long, not immediately.
24 pub const CLAIM_LEASE: Duration = Duration::from_secs(5 * 60);16 pub const CLAIM_LEASE: Duration = Duration::from_secs(5 * 60);
25-/// Largest page the list and claim functions return, whatever the caller asks for.
26 const MAX_PAGE: u32 = 200;17 const MAX_PAGE: u32 = 200;
27 18
28 const WEBHOOK_COLS: &str = "id, repo_id, url, events, active, created_at, updated_at";19 const WEBHOOK_COLS: &str = "id, repo_id, url, events, active, created_at, updated_at";
@@ -82,13 +73,8 @@ fn map_delivery(row: &Row) -> Result<Delivery> {
82 })73 })
83 }74 }
84 75
85-/// Headers the worker adds at send time. They are never kept in the stored request headers, so a
86-/// redelivery gets a fresh GUID and signature. Keep this list in step with `WORKER_HEADERS` in
87-/// forge-web's webhook worker.
88 const WORKER_OWNED_HEADERS: [&str; 2] = ["X-Forge-Delivery", "X-Forge-Signature-256"];76 const WORKER_OWNED_HEADERS: [&str; 2] = ["X-Forge-Delivery", "X-Forge-Signature-256"];
89 77
90-/// The stored headers with the worker-owned names removed. Text that is not a JSON object is
91-/// returned unchanged.
92 fn strip_worker_headers(raw: &str) -> String {78 fn strip_worker_headers(raw: &str) -> String {
93 match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(raw) {79 match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(raw) {
94 Ok(mut map) => {80 Ok(mut map) => {
@@ -103,21 +89,17 @@ fn strip_worker_headers(raw: &str) -> String {
103 }89 }
104 }90 }
105 91
106-/// JSON array of event names, in the order given.
107 fn events_json(events: &[WebhookEvent]) -> String {92 fn events_json(events: &[WebhookEvent]) -> String {
108 let names: Vec<&str> = events.iter().map(|e| e.as_str()).collect();93 let names: Vec<&str> = events.iter().map(|e| e.as_str()).collect();
109 serde_json::to_string(&names).unwrap_or_else(|_| "[]".to_string())94 serde_json::to_string(&names).unwrap_or_else(|_| "[]".to_string())
110 }95 }
111 96
112-/// A random GUID as 32 lowercase hex characters.
113 fn new_guid() -> String {97 fn new_guid() -> String {
114 let mut bytes = [0u8; 16];98 let mut bytes = [0u8; 16];
115 rand::fill(&mut bytes);99 rand::fill(&mut bytes);
116 hex::encode(bytes)100 hex::encode(bytes)
117 }101 }
118 102
119-/// The longest prefix of `body` that is at most [`MAX_RESPONSE_BODY_BYTES`] bytes and ends on a
120-/// character boundary.
121 fn truncate_body(body: &str) -> &str {103 fn truncate_body(body: &str) -> &str {
122 if body.len() <= MAX_RESPONSE_BODY_BYTES {104 if body.len() <= MAX_RESPONSE_BODY_BYTES {
123 return body;105 return body;
@@ -129,7 +111,6 @@ fn truncate_body(body: &str) -> &str {
129 &body[..end]111 &body[..end]
130 }112 }
131 113
132-/// Inserts a delivery row. Shared by `enqueue_delivery` and `redeliver`.
133 async fn insert_delivery(conn: &Connection, d: &Delivery) -> Result<()> {114 async fn insert_delivery(conn: &Connection, d: &Delivery) -> Result<()> {
134 let params = vec![115 let params = vec![
135 Value::Text(d.id.clone()),116 Value::Text(d.id.clone()),
@@ -184,12 +165,9 @@ fn pending_delivery(
184 }165 }
185 }166 }
186 167
187-/// Most webhooks one repository can have.
188 pub const MAX_WEBHOOKS: i64 = 20;168 pub const MAX_WEBHOOKS: i64 = 20;
189 169
190 impl Store {170 impl Store {
191- /// Creates a hook. `secret_sealed` is the `secret::seal` output as bytes. The hook starts
192- /// with `created_at == updated_at`.
193 pub async fn create_webhook(171 pub async fn create_webhook(
194 &self,172 &self,
195 repo_id: &str,173 repo_id: &str,
@@ -239,8 +217,6 @@ impl Store {
239 Ok(hook)217 Ok(hook)
240 }218 }
241 219
242- /// Replaces a hook's URL, events and active flag. `secret_sealed` `None` keeps the stored
243- /// secret; `Some` replaces it. Returns the updated hook, or `NotFound`.
244 pub async fn update_webhook(220 pub async fn update_webhook(
245 &self,221 &self,
246 id: &str,222 id: &str,
@@ -275,7 +251,6 @@ impl Store {
275 self.webhook(id).await?.ok_or(Error::NotFound)251 self.webhook(id).await?.ok_or(Error::NotFound)
276 }252 }
277 253
278- /// Deletes a hook and its deliveries in one transaction. `NotFound` if it does not exist.
279 pub async fn delete_webhook(&self, id: &str) -> Result<()> {254 pub async fn delete_webhook(&self, id: &str) -> Result<()> {
280 let conn = self.inner.conn.lock().await;255 let conn = self.inner.conn.lock().await;
281 let tx = conn.unchecked_transaction().await.map_err(db_err)?;256 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
@@ -296,7 +271,6 @@ impl Store {
296 finish(tx, outcome).await271 finish(tx, outcome).await
297 }272 }
298 273
299- /// One hook, or `None`. The secret is not included.
300 pub async fn webhook(&self, id: &str) -> Result<Option<Webhook>> {274 pub async fn webhook(&self, id: &str) -> Result<Option<Webhook>> {
301 let conn = self.read_conn().await;275 let conn = self.read_conn().await;
302 fetch_opt(276 fetch_opt(
@@ -308,8 +282,6 @@ impl Store {
308 .await282 .await
309 }283 }
310 284
311- /// The repo's hooks, oldest first, each with the state and stamp of its most recent delivery
312- /// (`None` when it has none yet).
313 pub async fn list_webhooks(285 pub async fn list_webhooks(
314 &self,286 &self,
315 repo_id: &str,287 repo_id: &str,
@@ -337,7 +309,6 @@ impl Store {
337 .await309 .await
338 }310 }
339 311
340- /// Active hooks of the repo that subscribe to `event`, oldest first.
341 pub async fn hooks_for_event(312 pub async fn hooks_for_event(
342 &self,313 &self,
343 repo_id: &str,314 repo_id: &str,
@@ -360,8 +331,6 @@ impl Store {
360 .collect())331 .collect())
361 }332 }
362 333
363- /// The plaintext secret of a hook, opened with the instance key. `NotFound` if the hook is
364- /// gone. A wrong key or a tampered value is a `Crypto` error.
365 pub async fn webhook_secret(&self, id: &str, key: &[u8; 32]) -> Result<String> {334 pub async fn webhook_secret(&self, id: &str, key: &[u8; 32]) -> Result<String> {
366 let sealed = {335 let sealed = {
367 let conn = self.read_conn().await;336 let conn = self.read_conn().await;
@@ -380,8 +349,6 @@ impl Store {
380 String::from_utf8(plain).map_err(|_| Error::Crypto("webhook secret is not UTF-8".into()))349 String::from_utf8(plain).map_err(|_| Error::Crypto("webhook secret is not UTF-8".into()))
381 }350 }
382 351
383- /// Queues a delivery for a hook: state `Pending`, attempt 0, due now, with a new GUID.
384- /// `headers_json` is a JSON object of the request headers, and `body` the payload.
385 pub async fn enqueue_delivery(352 pub async fn enqueue_delivery(
386 &self,353 &self,
387 hook_id: &str,354 hook_id: &str,
@@ -402,10 +369,6 @@ impl Store {
402 Ok(delivery)369 Ok(delivery)
403 }370 }
404 371
405- /// Claims up to `limit` deliveries that are due at `now` (state `pending` or `failed`, with
406- /// `next_attempt_at <= now`). Each claimed row gets `attempt + 1` and its `next_attempt_at`
407- /// moved `CLAIM_LEASE` into the future, so it is not claimed again until that passes, even
408- /// if this worker crashes. Returns the claimed rows as they are after the update.
409 pub async fn claim_due_deliveries(&self, now: &str, limit: u32) -> Result<Vec<Delivery>> {372 pub async fn claim_due_deliveries(&self, now: &str, limit: u32) -> Result<Vec<Delivery>> {
410 let lease = stamp_after(CLAIM_LEASE);373 let lease = stamp_after(CLAIM_LEASE);
411 let limit = i64::from(limit.clamp(1, MAX_PAGE));374 let limit = i64::from(limit.clamp(1, MAX_PAGE));
@@ -447,8 +410,6 @@ impl Store {
447 finish(tx, outcome).await410 finish(tx, outcome).await
448 }411 }
449 412
450- /// The earliest `next_attempt_at` among pending and failed deliveries, or `None` when none is
451- /// pending. A claimed delivery carries its lease expiry here, so the lease counts as due time.
452 pub async fn next_delivery_due(&self) -> Result<Option<String>> {413 pub async fn next_delivery_due(&self) -> Result<Option<String>> {
453 let conn = self.read_conn().await;414 let conn = self.read_conn().await;
454 fetch_opt(415 fetch_opt(
@@ -462,9 +423,6 @@ impl Store {
462 .map(Option::flatten)423 .map(Option::flatten)
463 }424 }
464 425
465- /// Records the outcome of one attempt. See [`AttemptOutcome`] for the resulting state.
466- /// On success `delivered_at` is stamped and `next_attempt_at` is cleared. The response body
467- /// is truncated to 64 KiB. `NotFound` if the delivery does not exist.
468 pub async fn record_delivery_result(&self, id: &str, outcome: &AttemptOutcome) -> Result<()> {426 pub async fn record_delivery_result(&self, id: &str, outcome: &AttemptOutcome) -> Result<()> {
469 let state = if outcome.ok {427 let state = if outcome.ok {
470 DeliveryState::Ok428 DeliveryState::Ok
@@ -515,7 +473,6 @@ impl Store {
515 Ok(())473 Ok(())
516 }474 }
517 475
518- /// The hook's most recent deliveries, newest first. `limit` is clamped to 1..=200.
519 pub async fn list_deliveries(&self, hook_id: &str, limit: u32) -> Result<Vec<Delivery>> {476 pub async fn list_deliveries(&self, hook_id: &str, limit: u32) -> Result<Vec<Delivery>> {
520 let conn = self.read_conn().await;477 let conn = self.read_conn().await;
521 fetch_all(478 fetch_all(
@@ -530,7 +487,6 @@ impl Store {
530 .await487 .await
531 }488 }
532 489
533- /// One delivery, or `None`.
534 pub async fn delivery(&self, id: &str) -> Result<Option<Delivery>> {490 pub async fn delivery(&self, id: &str) -> Result<Option<Delivery>> {
535 let conn = self.read_conn().await;491 let conn = self.read_conn().await;
536 fetch_opt(492 fetch_opt(
@@ -542,10 +498,6 @@ impl Store {
542 .await498 .await
543 }499 }
544 500
545- /// Queues a new delivery that copies `id`'s hook, event, action, headers and body. It gets
546- /// a new GUID. The copied headers drop `X-Forge-Delivery` and `X-Forge-Signature-256`, which
547- /// the worker adds again at send time with the new GUID and a fresh signature. `NotFound` if
548- /// `id` does not exist.
549 pub async fn redeliver(&self, id: &str) -> Result<Delivery> {501 pub async fn redeliver(&self, id: &str) -> Result<Delivery> {
550 let conn = self.inner.conn.lock().await;502 let conn = self.inner.conn.lock().await;
551 let original = fetch_opt(503 let original = fetch_opt(
@@ -567,8 +519,6 @@ impl Store {
567 Ok(copy)519 Ok(copy)
568 }520 }
569 521
570- /// Retention: deletes deliveries created before `cutoff` (an RFC 3339 UTC stamp). Returns
571- /// the number removed.
572 pub async fn purge_deliveries_before(&self, cutoff: &str) -> Result<u64> {522 pub async fn purge_deliveries_before(&self, cutoff: &str) -> Result<u64> {
573 let conn = self.inner.conn.lock().await;523 let conn = self.inner.conn.lock().await;
574 conn.execute(524 conn.execute(
@@ -635,8 +585,6 @@ mod tests {
635 col_int(&row, 0).unwrap()585 col_int(&row, 0).unwrap()
636 }586 }
637 587
638- /// Hook CRUD, the sealed secret and event filters. Each scenario has its own
639- /// repo, since listings and filters are per repo.
640 #[tokio::test]588 #[tokio::test]
641 async fn hook_crud_secret_and_event_filters() {589 async fn hook_crud_secret_and_event_filters() {
642 let (store, tahinli, _repo, _dir) = setup().await;590 let (store, tahinli, _repo, _dir) = setup().await;
@@ -696,7 +644,6 @@ mod tests {
696 Err(Error::NotFound)644 Err(Error::NotFound)
697 ));645 ));
698 646
699- // the sealed secret
700 let repo = store647 let repo = store
701 .create_repo(&tahinli.id, "secret", "", Visibility::Public, "main")648 .create_repo(&tahinli.id, "secret", "", Visibility::Public, "main")
702 .await649 .await
@@ -708,7 +655,6 @@ mod tests {
708 "s3cr3t"655 "s3cr3t"
709 );656 );
710 657
711- // The stored bytes are the sealed form, never the plaintext.
712 let raw = {658 let raw = {
713 let conn = store.inner.conn.lock().await;659 let conn = store.inner.conn.lock().await;
714 let mut rows = conn660 let mut rows = conn
@@ -758,7 +704,6 @@ mod tests {
758 ));704 ));
759 }705 }
760 706
761- // event filters
762 let repo = store707 let repo = store
763 .create_repo(&tahinli.id, "events", "", Visibility::Public, "main")708 .create_repo(&tahinli.id, "events", "", Visibility::Public, "main")
764 .await709 .await
@@ -845,7 +790,6 @@ mod tests {
845 assert!(d.next_attempt_at.as_deref().unwrap() > now_stamp().as_str());790 assert!(d.next_attempt_at.as_deref().unwrap() > now_stamp().as_str());
846 }791 }
847 792
848- // Still within the lease: nothing is due.
849 assert!(793 assert!(
850 store794 store
851 .claim_due_deliveries(&now_stamp(), 10)795 .claim_due_deliveries(&now_stamp(), 10)
@@ -854,7 +798,6 @@ mod tests {
854 .is_empty()798 .is_empty()
855 );799 );
856 800
857- // After the lease has passed, the rows are claimable again.
858 let later_claims = store801 let later_claims = store
859 .claim_due_deliveries(&later(Duration::from_secs(3600)), 10)802 .claim_due_deliveries(&later(Duration::from_secs(3600)), 10)
860 .await803 .await
@@ -900,7 +843,6 @@ mod tests {
900 .await843 .await
901 .unwrap();844 .unwrap();
902 845
903- // First attempt fails and schedules a retry.
904 store.claim_due_deliveries(&now_stamp(), 10).await.unwrap();846 store.claim_due_deliveries(&now_stamp(), 10).await.unwrap();
905 store847 store
906 .record_delivery_result(848 .record_delivery_result(
@@ -932,7 +874,6 @@ mod tests {
932 Some(DeliveryState::Failed)874 Some(DeliveryState::Failed)
933 );875 );
934 876
935- // The retry is claimable once it is due, and succeeds.
936 assert!(877 assert!(
937 store878 store
938 .claim_due_deliveries(&now_stamp(), 10)879 .claim_due_deliveries(&now_stamp(), 10)
@@ -963,7 +904,6 @@ mod tests {
963 assert!(ok.delivered_at.is_some());904 assert!(ok.delivered_at.is_some());
964 assert!(ok.next_attempt_at.is_none());905 assert!(ok.next_attempt_at.is_none());
965 906
966- // A second delivery gives up with no retry scheduled.
967 let g = store907 let g = store
968 .enqueue_delivery(&hook.id, WebhookEvent::Push, "", "{}", "{}")908 .enqueue_delivery(&hook.id, WebhookEvent::Push, "", "{}", "{}")
969 .await909 .await
@@ -999,12 +939,10 @@ mod tests {
999 Err(Error::NotFound)939 Err(Error::NotFound)
1000 ));940 ));
1001 941
1002- // a response body is cut to 64 KiB on a character boundary
1003 let d = store942 let d = store
1004 .enqueue_delivery(&hook.id, WebhookEvent::Push, "", "{}", "{}")943 .enqueue_delivery(&hook.id, WebhookEvent::Push, "", "{}", "{}")
1005 .await944 .await
1006 .unwrap();945 .unwrap();
1007- // Multi-byte characters, so the cut must back off to a boundary.
1008 let body = "é".repeat(MAX_RESPONSE_BODY_BYTES);946 let body = "é".repeat(MAX_RESPONSE_BODY_BYTES);
1009 store947 store
1010 .record_delivery_result(948 .record_delivery_result(
@@ -1028,7 +966,6 @@ mod tests {
1028 assert!(stored.len() > MAX_RESPONSE_BODY_BYTES - 4);966 assert!(stored.len() > MAX_RESPONSE_BODY_BYTES - 4);
1029 }967 }
1030 968
1031- /// Redelivery copies the request with a new GUID and drops the worker's headers.
1032 #[tokio::test]969 #[tokio::test]
1033 async fn redelivery_copies_and_drops_worker_headers() {970 async fn redelivery_copies_and_drops_worker_headers() {
1034 let (store, tahinli, repo, _dir) = setup().await;971 let (store, tahinli, repo, _dir) = setup().await;
@@ -1046,7 +983,6 @@ mod tests {
1046 )983 )
1047 .await984 .await
1048 .unwrap();985 .unwrap();
1049- // Rebuild the headers with the real GUID so the replacement can be checked.
1050 let original = {986 let original = {
1051 let conn = store.inner.conn.lock().await;987 let conn = store.inner.conn.lock().await;
1052 conn.execute(988 conn.execute(
@@ -1077,7 +1013,6 @@ mod tests {
1077 assert_eq!(copy.event, WebhookEvent::PullRequest);1013 assert_eq!(copy.event, WebhookEvent::PullRequest);
1078 assert_eq!(copy.action, "opened");1014 assert_eq!(copy.action, "opened");
1079 assert_eq!(copy.request_body, original.request_body);1015 assert_eq!(copy.request_body, original.request_body);
1080- // The worker-owned headers are dropped; the worker adds the new GUID and signature.
1081 assert_eq!(copy.request_headers, r#"{"X-Forge-Event":"pull_request"}"#);1016 assert_eq!(copy.request_headers, r#"{"X-Forge-Event":"pull_request"}"#);
1082 assert_eq!(copy.state, DeliveryState::Pending);1017 assert_eq!(copy.state, DeliveryState::Pending);
1083 assert_eq!(copy.attempt, 0);1018 assert_eq!(copy.attempt, 0);
@@ -1091,7 +1026,6 @@ mod tests {
1091 Err(Error::NotFound)1026 Err(Error::NotFound)
1092 ));1027 ));
1093 1028
1094- // headers the worker sent replace the stored ones, and redelivery drops them
1095 let hook = hook_at(&store, &tahinli, &repo, "https://sent.example").await;1029 let hook = hook_at(&store, &tahinli, &repo, "https://sent.example").await;
1096 let queued = store1030 let queued = store
1097 .enqueue_delivery(1031 .enqueue_delivery(
@@ -1111,7 +1045,6 @@ mod tests {
1111 })1045 })
1112 .to_string();1046 .to_string();
1113 1047
1114- // A `None` outcome keeps what was stored at enqueue time.
1115 store1048 store
1116 .record_delivery_result(1049 .record_delivery_result(
1117 &queued.id,1050 &queued.id,
@@ -1130,7 +1063,6 @@ mod tests {
1130 r#"{"Content-Type":"application/json","X-Forge-Event":"push"}"#1063 r#"{"Content-Type":"application/json","X-Forge-Event":"push"}"#
1131 );1064 );
1132 1065
1133- // A `Some` outcome overwrites them with the headers the worker actually sent.
1134 store1066 store
1135 .record_delivery_result(1067 .record_delivery_result(
1136 &queued.id,1068 &queued.id,
@@ -1146,7 +1078,6 @@ mod tests {
1146 let stored = store.delivery(&queued.id).await.unwrap().unwrap();1078 let stored = store.delivery(&queued.id).await.unwrap().unwrap();
1147 assert_eq!(stored.request_headers, sent);1079 assert_eq!(stored.request_headers, sent);
1148 1080
1149- // Redelivery copies the headers without the GUID and signature.
1150 let copy = store.redeliver(&queued.id).await.unwrap();1081 let copy = store.redeliver(&queued.id).await.unwrap();
1151 assert_eq!(1082 assert_eq!(
1152 copy.request_headers,1083 copy.request_headers,
@@ -1194,7 +1125,6 @@ mod tests {
1194 .unwrap()1125 .unwrap()
1195 .is_empty()1126 .is_empty()
1196 );1127 );
1197- // The hook itself is kept.
1198 assert!(store.webhook(&hook.id).await.unwrap().is_some());1128 assert!(store.webhook(&hook.id).await.unwrap().is_some());
1199 }1129 }
1200 1130
crates/forge-core/src/store/wiki.rsmodified+0 -6
@@ -1,11 +1,7 @@
1-//! Wiki switch per repo. The pages live in git (see forge-git `wiki.rs`); the database only says
2-//! whether the repo's wiki is on. Migration `0027_wiki.sql` adds `repos.wiki_enabled`, default on.
3-
4 use super::{Store, col_bool, db_err};1 use super::{Store, col_bool, db_err};
5 use crate::error::{Error, Result};2 use crate::error::{Error, Result};
6 3
7 impl Store {4 impl Store {
8- /// Whether the repo's wiki is on. `NotFound` when the repo does not exist.
9 pub async fn wiki_enabled(&self, repo_id: &str) -> Result<bool> {5 pub async fn wiki_enabled(&self, repo_id: &str) -> Result<bool> {
10 let conn = self.read_conn().await;6 let conn = self.read_conn().await;
11 let mut rows = conn7 let mut rows = conn
@@ -21,7 +17,6 @@ impl Store {
21 }17 }
22 }18 }
23 19
24- /// Turns the repo's wiki on or off. Turning it off hides the wiki; the git data stays on disk.
25 pub async fn set_wiki_enabled(&self, repo_id: &str, enabled: bool) -> Result<()> {20 pub async fn set_wiki_enabled(&self, repo_id: &str, enabled: bool) -> Result<()> {
26 let conn = self.inner.conn.lock().await;21 let conn = self.inner.conn.lock().await;
27 let n = conn22 let n = conn
@@ -61,7 +56,6 @@ mod tests {
61 store.set_wiki_enabled(&repo.id, true).await.unwrap();56 store.set_wiki_enabled(&repo.id, true).await.unwrap();
62 assert!(store.wiki_enabled(&repo.id).await.unwrap(), "switched on");57 assert!(store.wiki_enabled(&repo.id).await.unwrap(), "switched on");
63 58
64- // An id that is no repo is not found, for read and for write.
65 assert!(59 assert!(
66 matches!(60 matches!(
67 store.wiki_enabled("01ARZ3NDEKTSV4RRFFQ69G5FAV").await,61 store.wiki_enabled("01ARZ3NDEKTSV4RRFFQ69G5FAV").await,
crates/forge-core/src/suggestions.rsmodified+0 -19
@@ -1,27 +1,15 @@
1-//! Suggested changes in review comments. A comment whose body holds a fenced block opened with
2-//! ```suggestion proposes replacing the commented line with the lines of that block. This module
3-//! splits a body into text and suggestion parts, and computes the replacement of one line of a
4-//! file. The web layer checks the replacement against the head and the git layer commits it.
5-
6-/// One part of a comment body: markdown text, or the lines of a suggestion block.
7 #[derive(Debug, Clone, PartialEq, Eq)]1 #[derive(Debug, Clone, PartialEq, Eq)]
8 pub enum Part {2 pub enum Part {
9 Text(String),3 Text(String),
10 Suggestion(Vec<String>),4 Suggestion(Vec<String>),
11 }5 }
12 6
13-/// Why a suggestion cannot replace a line.
14 #[derive(Debug, Clone, Copy, PartialEq, Eq)]7 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15 pub enum ApplyError {8 pub enum ApplyError {
16- /// The file has no such line.
17 OutOfRange,9 OutOfRange,
18- /// The line no longer reads what the comment was written against.
19 Changed,10 Changed,
20 }11 }
21 12
22-/// Splits a comment body into text and suggestion parts, in order. A suggestion opens with three
23-/// or more backticks and the word `suggestion`, and closes with a line of at least as many
24-/// backticks. A fence that never closes is text, as is any other code fence.
25 pub fn split_body(body: &str) -> Vec<Part> {13 pub fn split_body(body: &str) -> Vec<Part> {
26 let lines: Vec<&str> = body.split('\n').collect();14 let lines: Vec<&str> = body.split('\n').collect();
27 let mut parts = Vec::new();15 let mut parts = Vec::new();
@@ -53,20 +41,16 @@ pub fn split_body(body: &str) -> Vec<Part> {
53 parts41 parts
54 }42 }
55 43
56-/// The number of backticks of a line that opens a suggestion block, if it does.
57 fn open_fence(line: &str) -> Option<usize> {44 fn open_fence(line: &str) -> Option<usize> {
58 let ticks = line.bytes().take_while(|&b| b == b'`').count();45 let ticks = line.bytes().take_while(|&b| b == b'`').count();
59 (ticks >= 3 && line[ticks..].trim() == "suggestion").then_some(ticks)46 (ticks >= 3 && line[ticks..].trim() == "suggestion").then_some(ticks)
60 }47 }
61 48
62-/// Whether `line` closes a fence opened with `ticks` backticks.
63 fn closes_fence(line: &str, ticks: usize) -> bool {49 fn closes_fence(line: &str, ticks: usize) -> bool {
64 let trimmed = line.trim();50 let trimmed = line.trim();
65 trimmed.len() >= ticks && trimmed.bytes().all(|b| b == b'`')51 trimmed.len() >= ticks && trimmed.bytes().all(|b| b == b'`')
66 }52 }
67 53
68-/// The text of the commented line, read from the last line of a stored diff hunk. The hunk ends
69-/// at the commented line, and that line is an added or a context line. `None` for a deleted line.
70 pub fn hunk_line(diff_hunk: &str) -> Option<&str> {54 pub fn hunk_line(diff_hunk: &str) -> Option<&str> {
71 let last = diff_hunk.lines().last()?;55 let last = diff_hunk.lines().last()?;
72 match last.as_bytes().first()? {56 match last.as_bytes().first()? {
@@ -75,8 +59,6 @@ pub fn hunk_line(diff_hunk: &str) -> Option<&str> {
75 }59 }
76 }60 }
77 61
78-/// `text` with line `line` (1-based) replaced by `replacement`, when that line still reads
79-/// `expected`. An empty replacement deletes the line. The trailing newline of `text` is kept.
80 pub fn replace_line(62 pub fn replace_line(
81 text: &str,63 text: &str,
82 line: u32,64 line: u32,
@@ -156,7 +138,6 @@ mod tests {
156 138
157 #[test]139 #[test]
158 fn replace_line_cases() {140 fn replace_line_cases() {
159- // (text, 1-based line, expected line text, replacement, want)
160 type Case<'a> = (141 type Case<'a> = (
161 &'a str,142 &'a str,
162 u32,143 u32,
crates/forge-core/src/time.rsmodified+0 -14
@@ -1,5 +1,3 @@
1-//! UTC timestamps. Format: RFC 3339, 9 fractional digits, `Z` suffix.
2-
3 use std::time::Duration;1 use std::time::Duration;
4 2
5 use time::{3 use time::{
@@ -12,11 +10,9 @@ const FORMAT: &[FormatItem<'static>] =
12 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");10 format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");
13 11
14 fn format_stamp(at: OffsetDateTime) -> String {12 fn format_stamp(at: OffsetDateTime) -> String {
15- // The format description only uses fields that always format, so this cannot fail.
16 at.format(FORMAT).unwrap_or_default()13 at.format(FORMAT).unwrap_or_default()
17 }14 }
18 15
19-/// Current time as an RFC 3339 UTC string with 9 fractional digits and a `Z` suffix.
20 pub fn now_stamp() -> String {16 pub fn now_stamp() -> String {
21 format_stamp(OffsetDateTime::now_utc())17 format_stamp(OffsetDateTime::now_utc())
22 }18 }
@@ -31,40 +27,30 @@ pub fn now_unix() -> i64 {
31 i64::try_from(unix_now()).unwrap_or(0)27 i64::try_from(unix_now()).unwrap_or(0)
32 }28 }
33 29
34-/// The stamp for `now + after`, in the same format as [`now_stamp`].
35-/// Saturates at the maximum representable time instead of panicking.
36 pub fn stamp_after(after: Duration) -> String {30 pub fn stamp_after(after: Duration) -> String {
37 let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX);31 let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX);
38 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))32 format_stamp(OffsetDateTime::now_utc().saturating_add(delta))
39 }33 }
40 34
41-/// The stamp for `now - ago`, in the same format as [`now_stamp`]. Saturates at the minimum
42-/// representable time instead of panicking.
43 pub fn stamp_ago(ago: Duration) -> String {35 pub fn stamp_ago(ago: Duration) -> String {
44 let delta = SignedDuration::try_from(ago).unwrap_or(SignedDuration::MAX);36 let delta = SignedDuration::try_from(ago).unwrap_or(SignedDuration::MAX);
45 format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))37 format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))
46 }38 }
47 39
48-/// The stamp for Unix seconds `unix`, in the same format as [`now_stamp`]. `None` when the time is
49-/// out of the range the format covers.
50 pub fn stamp_from_unix(unix: i64) -> Option<String> {40 pub fn stamp_from_unix(unix: i64) -> Option<String> {
51 OffsetDateTime::from_unix_timestamp(unix)41 OffsetDateTime::from_unix_timestamp(unix)
52 .ok()42 .ok()
53 .map(format_stamp)43 .map(format_stamp)
54 }44 }
55 45
56-/// Unix seconds for a stamp written by [`now_stamp`]. `None` when the text is not a stamp.
57 pub fn stamp_to_unix(stamp: &str) -> Option<i64> {46 pub fn stamp_to_unix(stamp: &str) -> Option<i64> {
58 OffsetDateTime::parse(stamp, &Rfc3339)47 OffsetDateTime::parse(stamp, &Rfc3339)
59 .ok()48 .ok()
60 .map(OffsetDateTime::unix_timestamp)49 .map(OffsetDateTime::unix_timestamp)
61 }50 }
62 51
63-/// The shortest sleep, so a due time that has already passed does not spin a worker loop.
64 const MIN_SLEEP: Duration = Duration::from_secs(1);52 const MIN_SLEEP: Duration = Duration::from_secs(1);
65 53
66-/// How long a worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to
67-/// `MIN_SLEEP..=backstop`. `None` (nothing due) or an unparsable stamp gives `backstop`.
68 pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration {54 pub fn sleep_until(next_due: Option<&str>, now: OffsetDateTime, backstop: Duration) -> Duration {
69 let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else {55 let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else {
70 return backstop;56 return backstop;
crates/forge-core/src/token.rsmodified+0 -11
@@ -1,23 +1,15 @@
1-//! Access tokens: `forge_` + base64url(32 random bytes). Only the sha256 hash is stored.
2-
3 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};1 use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
4 use sha2::{Digest, Sha256};2 use sha2::{Digest, Sha256};
5 use subtle::ConstantTimeEq;3 use subtle::ConstantTimeEq;
6 4
7-/// Fresh random 32 bytes from the thread RNG, a CSPRNG seeded from the OS. It is
8-/// infallible, so callers need no error path.
9 pub(crate) fn random_32() -> [u8; 32] {5 pub(crate) fn random_32() -> [u8; 32] {
10 let mut buf = [0u8; 32];6 let mut buf = [0u8; 32];
11 rand::fill(&mut buf);7 rand::fill(&mut buf);
12 buf8 buf
13 }9 }
14 10
15-/// Alphabet for codes typed by people: lowercase letters and digits 2-9, without look-alikes
16-/// such as `l`, `o`, `0` and `1`. It has exactly 32 symbols, so the low five bits of a random
17-/// byte pick one uniformly.
18 pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";11 pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";
19 12
20-/// `len` random characters from [`READABLE_ALPHABET`].
21 pub fn random_readable(len: usize) -> String {13 pub fn random_readable(len: usize) -> String {
22 let mut buf = vec![0u8; len];14 let mut buf = vec![0u8; len];
23 rand::fill(buf.as_mut_slice());15 rand::fill(buf.as_mut_slice());
@@ -34,7 +26,6 @@ pub fn generate_token() -> String {
34 format!("forge_{}", random_b64url())26 format!("forge_{}", random_b64url())
35 }27 }
36 28
37-/// Hex-encoded sha256 of the token.
38 pub fn hash_token(token: &str) -> String {29 pub fn hash_token(token: &str) -> String {
39 hex::encode(Sha256::digest(token.as_bytes()))30 hex::encode(Sha256::digest(token.as_bytes()))
40 }31 }
@@ -54,7 +45,6 @@ pub fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result<(u64, St
54 Ok((total, hex::encode(hasher.finalize())))45 Ok((total, hex::encode(hasher.finalize())))
55 }46 }
56 47
57-/// Constant-time byte comparison.
58 pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {48 pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
59 a.ct_eq(b).into()49 a.ct_eq(b).into()
60 }50 }
@@ -77,7 +67,6 @@ mod tests {
77 67
78 #[test]68 #[test]
79 fn hash_is_hex_sha256() {69 fn hash_is_hex_sha256() {
80- // Known vector: sha256("abc").
81 assert_eq!(70 assert_eq!(
82 hash_token("abc"),71 hash_token("abc"),
83 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"72 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
crates/forge-core/src/totp.rsmodified+0 -25
@@ -1,9 +1,3 @@
1-//! Two-factor helpers: TOTP (RFC 6238) over HMAC-SHA1 with 6 digits and a 30 second step,
2-//! RFC 4648 base32 for the shared secret, and recovery codes.
3-//!
4-//! Codes are checked at the current step and one step either side. The caller records the
5-//! matched step so that a code is accepted only once (see `Store::accept_totp_step`).
6-
7 use hmac::{Hmac, KeyInit, Mac};1 use hmac::{Hmac, KeyInit, Mac};
8 use sha1::Sha1;2 use sha1::Sha1;
9 use sha2::{Digest, Sha256};3 use sha2::{Digest, Sha256};
@@ -11,29 +5,22 @@ use sha2::{Digest, Sha256};
11 use crate::error::{Error, Result};5 use crate::error::{Error, Result};
12 use crate::token::{constant_time_eq, random_readable};6 use crate::token::{constant_time_eq, random_readable};
13 7
14-/// Shared secret length in bytes (160 bits, the RFC 4226 recommendation).
15 pub const SECRET_LEN: usize = 20;8 pub const SECRET_LEN: usize = 20;
16-/// Seconds per time step.
17 pub const STEP_SECS: u64 = 30;9 pub const STEP_SECS: u64 = 30;
18-/// Digits in a code.
19 pub const DIGITS: usize = 6;10 pub const DIGITS: usize = 6;
20-/// Steps accepted on each side of the current one.
21 pub const SKEW_STEPS: i64 = 1;11 pub const SKEW_STEPS: i64 = 1;
22 12
23 const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";13 const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
24 14
25 type HmacSha1 = Hmac<Sha1>;15 type HmacSha1 = Hmac<Sha1>;
26 16
27-/// A fresh random secret.
28 pub fn new_secret() -> [u8; SECRET_LEN] {17 pub fn new_secret() -> [u8; SECRET_LEN] {
29 let mut secret = [0u8; SECRET_LEN];18 let mut secret = [0u8; SECRET_LEN];
30 rand::fill(&mut secret);19 rand::fill(&mut secret);
31 secret20 secret
32 }21 }
33 22
34-/// HOTP (RFC 4226) with HMAC-SHA1, reduced to [`DIGITS`] digits.
35 pub fn hotp(secret: &[u8], counter: u64) -> u32 {23 pub fn hotp(secret: &[u8], counter: u64) -> u32 {
36- // HMAC accepts keys of any length, so construction cannot fail.
37 let mut mac = <HmacSha1 as KeyInit>::new_from_slice(secret).expect("HMAC takes any key length");24 let mut mac = <HmacSha1 as KeyInit>::new_from_slice(secret).expect("HMAC takes any key length");
38 mac.update(&counter.to_be_bytes());25 mac.update(&counter.to_be_bytes());
39 let tag = mac.finalize().into_bytes();26 let tag = mac.finalize().into_bytes();
@@ -47,25 +34,20 @@ pub fn hotp(secret: &[u8], counter: u64) -> u32 {
47 binary % 10u32.pow(DIGITS as u32)34 binary % 10u32.pow(DIGITS as u32)
48 }35 }
49 36
50-/// The time step containing `unix_secs`.
51 pub fn step_for(unix_secs: u64) -> u64 {37 pub fn step_for(unix_secs: u64) -> u64 {
52 unix_secs / STEP_SECS38 unix_secs / STEP_SECS
53 }39 }
54 40
55-/// The zero-padded code for one step.
56 pub fn code_at(secret: &[u8], step: u64) -> String {41 pub fn code_at(secret: &[u8], step: u64) -> String {
57 format!("{:0width$}", hotp(secret, step), width = DIGITS)42 format!("{:0width$}", hotp(secret, step), width = DIGITS)
58 }43 }
59 44
60-/// Checks `code` against the steps around `now_step`. Returns the matched step when it is
61-/// later than `last_step`, which is the replay guard. Any malformed code returns `None`.
62 pub fn verify(secret: &[u8], code: &str, now_step: u64, last_step: u64) -> Option<u64> {45 pub fn verify(secret: &[u8], code: &str, now_step: u64, last_step: u64) -> Option<u64> {
63 if code.len() != DIGITS || !code.bytes().all(|b| b.is_ascii_digit()) {46 if code.len() != DIGITS || !code.bytes().all(|b| b.is_ascii_digit()) {
64 return None;47 return None;
65 }48 }
66 let now = i64::try_from(now_step).ok()?;49 let now = i64::try_from(now_step).ok()?;
67 let mut matched = None;50 let mut matched = None;
68- // Every candidate is compared, so timing does not reveal which step matched.
69 for delta in -SKEW_STEPS..=SKEW_STEPS {51 for delta in -SKEW_STEPS..=SKEW_STEPS {
70 let Some(step) = now.checked_add(delta).and_then(|s| u64::try_from(s).ok()) else {52 let Some(step) = now.checked_add(delta).and_then(|s| u64::try_from(s).ok()) else {
71 continue;53 continue;
@@ -78,7 +60,6 @@ pub fn verify(secret: &[u8], code: &str, now_step: u64, last_step: u64) -> Optio
78 matched.filter(|&step| step > last_step)60 matched.filter(|&step| step > last_step)
79 }61 }
80 62
81-/// RFC 4648 base32, uppercase, without padding. This is the form authenticator apps expect.
82 pub fn base32_encode(data: &[u8]) -> String {63 pub fn base32_encode(data: &[u8]) -> String {
83 let mut out = String::with_capacity(data.len().div_ceil(5) * 8);64 let mut out = String::with_capacity(data.len().div_ceil(5) * 8);
84 let mut buffer: u64 = 0;65 let mut buffer: u64 = 0;
@@ -101,7 +82,6 @@ pub fn base32_encode(data: &[u8]) -> String {
101 out82 out
102 }83 }
103 84
104-/// Decodes base32 case-insensitively. Spaces and `=` padding are ignored.
105 pub fn base32_decode(input: &str) -> Result<Vec<u8>> {85 pub fn base32_decode(input: &str) -> Result<Vec<u8>> {
106 let mut out = Vec::with_capacity(input.len() * 5 / 8);86 let mut out = Vec::with_capacity(input.len() * 5 / 8);
107 let mut buffer: u64 = 0;87 let mut buffer: u64 = 0;
@@ -125,7 +105,6 @@ pub fn base32_decode(input: &str) -> Result<Vec<u8>> {
125 Ok(out)105 Ok(out)
126 }106 }
127 107
128-/// The `otpauth://` URI that authenticator apps import. `account` is the username.
129 pub fn otpauth_uri(account: &str, secret: &[u8]) -> String {108 pub fn otpauth_uri(account: &str, secret: &[u8]) -> String {
130 format!(109 format!(
131 "otpauth://totp/forge:{account}?secret={}&issuer=forge",110 "otpauth://totp/forge:{account}?secret={}&issuer=forge",
@@ -133,14 +112,11 @@ pub fn otpauth_uri(account: &str, secret: &[u8]) -> String {
133 )112 )
134 }113 }
135 114
136-/// A new recovery code, shown as `xxxx-xxxx`.
137 pub fn new_recovery_code() -> String {115 pub fn new_recovery_code() -> String {
138 let raw = random_readable(8);116 let raw = random_readable(8);
139 format!("{}-{}", &raw[..4], &raw[4..])117 format!("{}-{}", &raw[..4], &raw[4..])
140 }118 }
141 119
142-/// Hex sha256 of a recovery code after normalization: lowercase, with dashes and spaces removed.
143-/// Used both when storing and when checking, so the typed form does not matter.
144 pub fn recovery_code_hash(code: &str) -> String {120 pub fn recovery_code_hash(code: &str) -> String {
145 let normalized: String = code121 let normalized: String = code
146 .chars()122 .chars()
@@ -154,7 +130,6 @@ pub fn recovery_code_hash(code: &str) -> String {
154 mod tests {130 mod tests {
155 use super::*;131 use super::*;
156 132
157- /// RFC 6238 appendix B, SHA-1 row. The 8-digit codes reduce to the 6-digit ones below.
158 const RFC_KEY: &[u8] = b"12345678901234567890";133 const RFC_KEY: &[u8] = b"12345678901234567890";
159 134
160 #[test]135 #[test]
crates/forge-core/src/tz.rsmodified+0 -13
@@ -1,26 +1,19 @@
1-//! IANA timezone helpers backed by jiff's bundled tzdb, so results do not depend on the host.
2-
3 use jiff::{Timestamp, civil, tz::TimeZone};1 use jiff::{Timestamp, civil, tz::TimeZone};
4 2
5 use crate::error::{Error, Result};3 use crate::error::{Error, Result};
6 4
7-/// Resolves an IANA name, falling back to UTC for anything unknown.
8 fn zone_or_utc(tz: &str) -> TimeZone {5 fn zone_or_utc(tz: &str) -> TimeZone {
9 TimeZone::get(tz).unwrap_or(TimeZone::UTC)6 TimeZone::get(tz).unwrap_or(TimeZone::UTC)
10 }7 }
11 8
12-/// The civil date and clock time `ts` falls on in `tz`, DST-aware. Unknown zones fall back to UTC.
13 pub fn local_datetime(ts: Timestamp, tz: &str) -> civil::DateTime {9 pub fn local_datetime(ts: Timestamp, tz: &str) -> civil::DateTime {
14 ts.to_zoned_datetime(zone_or_utc(tz)).datetime()10 ts.to_zoned_datetime(zone_or_utc(tz)).datetime()
15 }11 }
16 12
17-/// The civil date `ts` falls on in `tz`. Unknown zones fall back to UTC.
18 pub fn local_date(ts: Timestamp, tz: &str) -> civil::Date {13 pub fn local_date(ts: Timestamp, tz: &str) -> civil::Date {
19 local_datetime(ts, tz).date()14 local_datetime(ts, tz).date()
20 }15 }
21 16
22-/// Unix seconds for the start of the civil day `date` in `tz`, and for the start of the day after
23-/// it. `None` at the edge of the range jiff can represent. Unknown zones fall back to UTC.
24 pub fn day_span(date: civil::Date, tz: &str) -> Option<(i64, i64)> {17 pub fn day_span(date: civil::Date, tz: &str) -> Option<(i64, i64)> {
25 let zone = zone_or_utc(tz);18 let zone = zone_or_utc(tz);
26 let start = date19 let start = date
@@ -38,14 +31,12 @@ pub fn day_span(date: civil::Date, tz: &str) -> Option<(i64, i64)> {
38 Some((start.as_second(), next.as_second()))31 Some((start.as_second(), next.as_second()))
39 }32 }
40 33
41-/// Accepts only names known to the bundled tzdb, such as "Europe/Istanbul" or "UTC".
42 pub fn validate_timezone(name: &str) -> Result<()> {34 pub fn validate_timezone(name: &str) -> Result<()> {
43 TimeZone::get(name)35 TimeZone::get(name)
44 .map(|_| ())36 .map(|_| ())
45 .map_err(|_| Error::Invalid(format!("timezone {name:?}")))37 .map_err(|_| Error::Invalid(format!("timezone {name:?}")))
46 }38 }
47 39
48-/// Every known IANA name, sorted and without duplicates, for the timezone `<select>`.
49 pub fn all_timezones() -> Vec<String> {40 pub fn all_timezones() -> Vec<String> {
50 let mut names: Vec<String> = jiff::tz::db()41 let mut names: Vec<String> = jiff::tz::db()
51 .available()42 .available()
@@ -56,7 +47,6 @@ pub fn all_timezones() -> Vec<String> {
56 names47 names
57 }48 }
58 49
59-/// Absolute time for display, e.g. "2026-10-15 14:05 +03". Unknown zones fall back to UTC.
60 pub fn format_in_tz(unix: i64, tz: &str) -> String {50 pub fn format_in_tz(unix: i64, tz: &str) -> String {
61 let Ok(ts) = Timestamp::from_second(unix) else {51 let Ok(ts) = Timestamp::from_second(unix) else {
62 return "invalid time".to_string();52 return "invalid time".to_string();
@@ -65,14 +55,12 @@ pub fn format_in_tz(unix: i64, tz: &str) -> String {
65 .to_zoned_datetime(zone_or_utc(tz))55 .to_zoned_datetime(zone_or_utc(tz))
66 .strftime("%Y-%m-%d %H:%M %:z")56 .strftime("%Y-%m-%d %H:%M %:z")
67 .to_string();57 .to_string();
68- // Whole-hour offsets print as "+03" rather than "+03:00".
69 match formatted.strip_suffix(":00") {58 match formatted.strip_suffix(":00") {
70 Some(short) => short.to_string(),59 Some(short) => short.to_string(),
71 None => formatted,60 None => formatted,
72 }61 }
73 }62 }
74 63
75-/// Local clock time with its offset, e.g. "14:05 (UTC+03:00)". Unknown zones fall back to UTC.
76 pub fn local_time_now(tz: &str, now_unix: i64) -> String {64 pub fn local_time_now(tz: &str, now_unix: i64) -> String {
77 let Ok(ts) = Timestamp::from_second(now_unix) else {65 let Ok(ts) = Timestamp::from_second(now_unix) else {
78 return "invalid time".to_string();66 return "invalid time".to_string();
@@ -88,7 +76,6 @@ mod tests {
88 76
89 #[test]77 #[test]
90 fn formats_absolute_time_in_zone() {78 fn formats_absolute_time_in_zone() {
91- // 2026-10-15 11:05:00 UTC is 14:05 in Istanbul (UTC+03, no DST).
92 let unix = 1_792_062_300;79 let unix = 1_792_062_300;
93 assert_eq!(80 assert_eq!(
94 format_in_tz(unix, "Europe/Istanbul"),81 format_in_tz(unix, "Europe/Istanbul"),
crates/forge-core/src/webhooks.rsmodified+0 -31
@@ -1,11 +1,3 @@
1-//! Repo webhooks: the event names, the hook and delivery shapes. The stored shape is in
2-//! migrations/0011_webhooks.sql; the store functions live in store/webhooks.rs.
3-//!
4-//! A hook never carries its secret. The secret is sealed with the instance key (see `secret.rs`)
5-//! by the caller and stored as `secret_sealed`; it is read back only through
6-//! `Store::webhook_secret`.
7-
8-/// Every event a hook can subscribe to. The `as_str` names are stored and sent in `X-Forge-Event`.
9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]1 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10 pub enum WebhookEvent {2 pub enum WebhookEvent {
11 Push,3 Push,
@@ -51,9 +43,6 @@ impl WebhookEvent {
51 }43 }
52 }44 }
53 45
54-/// Delivery state. Stored as the `as_str` name.
55-/// `Pending`: queued, never attempted. `Failed`: an attempt failed and a retry is scheduled.
56-/// `Ok`: a 2xx response was received. `GaveUp`: no further attempts.
57 #[derive(Debug, Clone, Copy, PartialEq, Eq)]46 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
58 pub enum DeliveryState {47 pub enum DeliveryState {
59 Pending,48 Pending,
@@ -83,7 +72,6 @@ impl DeliveryState {
83 }72 }
84 }73 }
85 74
86-/// A repo webhook. Has no secret field; see `Store::webhook_secret`.
87 #[derive(Debug, Clone, PartialEq, Eq)]75 #[derive(Debug, Clone, PartialEq, Eq)]
88 pub struct Webhook {76 pub struct Webhook {
89 pub id: String,77 pub id: String,
@@ -95,56 +83,37 @@ pub struct Webhook {
95 pub updated_at: String,83 pub updated_at: String,
96 }84 }
97 85
98-/// One delivery attempt chain for one event. `request_*` is immutable; the rest is updated as
99-/// attempts happen.
100 #[derive(Debug, Clone, PartialEq, Eq)]86 #[derive(Debug, Clone, PartialEq, Eq)]
101 pub struct Delivery {87 pub struct Delivery {
102 pub id: String,88 pub id: String,
103 pub hook_id: String,89 pub hook_id: String,
104- /// The `X-Forge-Delivery` value.
105 pub guid: String,90 pub guid: String,
106 pub event: WebhookEvent,91 pub event: WebhookEvent,
107- /// The payload's action, or empty when the event has none.
108 pub action: String,92 pub action: String,
109- /// JSON object of the request headers that were sent.
110 pub request_headers: String,93 pub request_headers: String,
111 pub request_body: String,94 pub request_body: String,
112 pub state: DeliveryState,95 pub state: DeliveryState,
113- /// Attempts started. Incremented when the delivery is claimed.
114 pub attempt: u32,96 pub attempt: u32,
115- /// When the next attempt is due. `None` once the delivery is `Ok` or `GaveUp`.
116 pub next_attempt_at: Option<String>,97 pub next_attempt_at: Option<String>,
117 pub response_status: Option<u16>,98 pub response_status: Option<u16>,
118- /// JSON object of the response headers.
119 pub response_headers: Option<String>,99 pub response_headers: Option<String>,
120- /// The first 64 KiB of the response body.
121 pub response_body: Option<String>,100 pub response_body: Option<String>,
122- /// Transport error text, such as a refused connection or a blocked address.
123 pub error: Option<String>,101 pub error: Option<String>,
124 pub duration_ms: Option<u64>,102 pub duration_ms: Option<u64>,
125 pub created_at: String,103 pub created_at: String,
126 pub delivered_at: Option<String>,104 pub delivered_at: Option<String>,
127 }105 }
128 106
129-/// The outcome of one attempt, recorded by `Store::record_delivery_result`.
130-///
131-/// `ok` true sets the state to `Ok`. `ok` false with `next_attempt_at` set sets it to `Failed`
132-/// and schedules a retry. `ok` false with `next_attempt_at` `None` sets it to `GaveUp`.
133 #[derive(Debug, Clone, Default, PartialEq, Eq)]107 #[derive(Debug, Clone, Default, PartialEq, Eq)]
134 pub struct AttemptOutcome {108 pub struct AttemptOutcome {
135 pub ok: bool,109 pub ok: bool,
136 pub status: Option<u16>,110 pub status: Option<u16>,
137 pub response_headers: Option<String>,111 pub response_headers: Option<String>,
138- /// Truncated to 64 KiB by the store, at a character boundary.
139 pub response_body: Option<String>,112 pub response_body: Option<String>,
140 pub error: Option<String>,113 pub error: Option<String>,
141 pub duration_ms: Option<u64>,114 pub duration_ms: Option<u64>,
142 pub next_attempt_at: Option<String>,115 pub next_attempt_at: Option<String>,
143- /// The headers actually sent on this attempt, as a JSON object. When `Some`, it replaces the
144- /// stored request headers, so the delivery log shows what the receiver got (including the
145- /// GUID and signature the worker adds). `None` keeps what was stored at enqueue time.
146 pub request_headers: Option<String>,116 pub request_headers: Option<String>,
147 }117 }
148 118
149-/// Largest response body kept, in bytes.
150 pub const MAX_RESPONSE_BODY_BYTES: usize = 64 * 1024;119 pub const MAX_RESPONSE_BODY_BYTES: usize = 64 * 1024;
crates/forge-core/tests/integration/audit_store.rsmodified+1 -4
@@ -1,5 +1,3 @@
1-//! Store tests for the audit log: record, filtered listing, cursor paging and retention purge.
2-
3 use std::time::Duration;1 use std::time::Duration;
4 2
5 use forge_core::time::stamp_ago;3 use forge_core::time::stamp_ago;
@@ -68,7 +66,6 @@ async fn filters_by_actor_action_target_and_involved_user() {
68 .record_audit(&entry(AuditAction::SshKeyAdded, Some(&bob)))66 .record_audit(&entry(AuditAction::SshKeyAdded, Some(&bob)))
69 .await67 .await
70 .unwrap();68 .unwrap();
71- // Admin acts on bob: bob is the target, not the actor.
72 let mut reset = entry(AuditAction::PasswordResetByAdmin, Some(&tahinli));69 let mut reset = entry(AuditAction::PasswordResetByAdmin, Some(&tahinli));
73 reset.target_kind = "user".into();70 reset.target_kind = "user".into();
74 reset.target_id = bob.id.clone();71 reset.target_id = bob.id.clone();
@@ -121,7 +118,7 @@ async fn cursor_pages_newest_first_without_gaps() {
121 store.record_audit(&e).await.unwrap();118 store.record_audit(&e).await.unwrap();
122 written.push(e);119 written.push(e);
123 }120 }
124- written.reverse(); // newest first121+ written.reverse();
125 122
126 let filter = AuditFilter::default();123 let filter = AuditFilter::default();
127 let first = store.list_audit(&filter, None, 2).await.unwrap();124 let first = store.list_audit(&filter, None, 2).await.unwrap();
crates/forge-core/tests/integration/common.rsmodified+0 -2
@@ -1,5 +1,3 @@
1-//! Helpers shared by the store test modules.
2-
3 use std::path::{Path, PathBuf};1 use std::path::{Path, PathBuf};
4 2
5 use forge_core::Store;3 use forge_core::Store;
crates/forge-core/tests/integration/main.rsmodified+0 -2
@@ -1,5 +1,3 @@
1-//! Store integration tests for forge-core, built as one test binary.
2-
3 mod common;1 mod common;
4 2
5 mod audit_store;3 mod audit_store;
crates/forge-core/tests/integration/store_basic.rsmodified+0 -9
@@ -1,5 +1,3 @@
1-//! Store round-trip tests against a real turso database file in a temp directory.
2-
3 use forge_core::time::{stamp_after, stamp_ago};1 use forge_core::time::{stamp_after, stamp_ago};
4 use forge_core::{Error, Role, Visibility};2 use forge_core::{Error, Role, Visibility};
5 use std::time::Duration;3 use std::time::Duration;
@@ -339,7 +337,6 @@ async fn repo_create_and_case_insensitive_lookup() {
339 "expected Conflict, got {dup:?}"337 "expected Conflict, got {dup:?}"
340 );338 );
341 339
342- // Same name under another owner is fine.
343 let bob = store.create_user("bob", None, "h", false).await.unwrap();340 let bob = store.create_user("bob", None, "h", false).await.unwrap();
344 let bobs = store341 let bobs = store
345 .create_repo(&bob.id, "forge-demo", "", Visibility::Public, "trunk")342 .create_repo(&bob.id, "forge-demo", "", Visibility::Public, "trunk")
@@ -427,7 +424,6 @@ async fn push_event_is_recorded() {
427 .await424 .await
428 .unwrap();425 .unwrap();
429 426
430- // Count through a second connection to the same file.
431 let db = turso::Builder::new_local(path.to_str().unwrap())427 let db = turso::Builder::new_local(path.to_str().unwrap())
432 .build()428 .build()
433 .await429 .await
@@ -457,7 +453,6 @@ async fn reopening_keeps_data_and_migrations_are_idempotent() {
457 let store = open_store(&path).await;453 let store = open_store(&path).await;
458 store.create_user("tahinli", None, "h", true).await.unwrap();454 store.create_user("tahinli", None, "h", true).await.unwrap();
459 }455 }
460- // Open twice more: migrations must not re-run or fail.
461 let store = open_store(&path).await;456 let store = open_store(&path).await;
462 drop(store);457 drop(store);
463 let store = open_store(&path).await;458 let store = open_store(&path).await;
@@ -495,7 +490,6 @@ async fn create_first_admin_only_inserts_into_empty_table() {
495 assert_eq!(first.username, "Root");490 assert_eq!(first.username, "Root");
496 assert_eq!(store.user_count().await.unwrap(), 1);491 assert_eq!(store.user_count().await.unwrap(), 1);
497 492
498- // A second racing caller finds the table non-empty and gets None, leaving the row alone.
499 assert!(493 assert!(
500 store494 store
501 .create_first_admin("Intruder", None, "hash-x")495 .create_first_admin("Intruder", None, "hash-x")
@@ -530,7 +524,6 @@ async fn set_username_display_changes_only_capitalization() {
530 .expect("folded lookup still works");524 .expect("folded lookup still works");
531 assert_eq!(by_name.id, user.id);525 assert_eq!(by_name.id, user.id);
532 526
533- // A different name, even one differing only by case from the new display, is refused.
534 let err = store527 let err = store
535 .set_username_display(&user.id, "other")528 .set_username_display(&user.id, "other")
536 .await529 .await
@@ -566,7 +559,6 @@ async fn oci_sweep_keeps_a_blob_linked_within_the_grace_period() {
566 .await559 .await
567 .expect("link");560 .expect("link");
568 561
569- // A link made within the grace period belongs to a push whose manifest is not yet PUT.
570 let grace_cutoff = forge_core::time::stamp_ago(Duration::from_secs(3600));562 let grace_cutoff = forge_core::time::stamp_ago(Duration::from_secs(3600));
571 let kept = store563 let kept = store
572 .oci_sweep_unreferenced(&package.id, &grace_cutoff)564 .oci_sweep_unreferenced(&package.id, &grace_cutoff)
@@ -575,7 +567,6 @@ async fn oci_sweep_keeps_a_blob_linked_within_the_grace_period() {
575 assert!(kept.is_empty(), "a recent link is kept");567 assert!(kept.is_empty(), "a recent link is kept");
576 assert!(store.oci_digest_linked(&digest).await.expect("linked"));568 assert!(store.oci_digest_linked(&digest).await.expect("linked"));
577 569
578- // Once the link is older than the cutoff, the unreferenced digest is dropped.
579 let later_cutoff = stamp_after(Duration::from_secs(3600));570 let later_cutoff = stamp_after(Duration::from_secs(3600));
580 let dropped = store571 let dropped = store
581 .oci_sweep_unreferenced(&package.id, &later_cutoff)572 .oci_sweep_unreferenced(&package.id, &later_cutoff)
crates/forge-e2e/src/lib.rsmodified+1 -1
@@ -1 +1 @@
1-//! End-to-end tests for the forge binary. The tests live in `tests/e2e`.1+
crates/forge-e2e/tests/e2e/account_mail_e2e.rsmodified+0 -15
@@ -1,7 +1,3 @@
1-//! Black-box tests for the account mail flows: password reset over HTTP. Like the other e2e
2-//! tests, this starts the real `forge` binary. The log transport writes each mail to
3-//! `<data_dir>/mail-log/`, which is where the tests read the reset link from.
4-
5 use crate::common::{Http, Resp, cookie_named, input_value, launch_with, pick_ports};1 use crate::common::{Http, Resp, cookie_named, input_value, launch_with, pick_ports};
6 use std::fs;2 use std::fs;
7 use std::path::{Path, PathBuf};3 use std::path::{Path, PathBuf};
@@ -14,8 +10,6 @@ const LOG_TRANSPORT: &str = "\n[mail]\ntransport = \"log\"\n";
14 const OLD_PW: &str = "tahinli-old-password-1";10 const OLD_PW: &str = "tahinli-old-password-1";
15 const NEW_PW: &str = "tahinli-new-password-2";11 const NEW_PW: &str = "tahinli-new-password-2";
16 12
17-/// Creates tahinli with a verified address. Bob has an address that is not verified. Runs before
18-/// the server starts, like the other e2e tests.
19 async fn seed(dir: &Path) {13 async fn seed(dir: &Path) {
20 let store = Store::open(&dir.join("forge.db"))14 let store = Store::open(&dir.join("forge.db"))
21 .await15 .await
@@ -38,8 +32,6 @@ async fn seed(dir: &Path) {
38 .await32 .await
39 .expect("verify")33 .expect("verify")
40 .expect("verified");34 .expect("verified");
41- // The worker sends nothing while mail is off, and it is off by default. The log transport
42- // ignores the host, but enabling mail needs one.
43 store35 store
44 .update_mail_settings(&forge_core::mail::MailSettingsUpdate {36 .update_mail_settings(&forge_core::mail::MailSettingsUpdate {
45 host: "smtp.example",37 host: "smtp.example",
@@ -64,7 +56,6 @@ async fn seed(dir: &Path) {
64 .expect("bob");56 .expect("bob");
65 }57 }
66 58
67-/// The text of every mail the log transport has written so far.
68 fn mail_log(dir: &Path) -> String {59 fn mail_log(dir: &Path) -> String {
69 let log: PathBuf = dir.join("mail-log");60 let log: PathBuf = dir.join("mail-log");
70 let Ok(entries) = fs::read_dir(&log) else {61 let Ok(entries) = fs::read_dir(&log) else {
@@ -77,7 +68,6 @@ fn mail_log(dir: &Path) -> String {
77 .join("\n----\n")68 .join("\n----\n")
78 }69 }
79 70
80-/// Waits until a mail containing `marker` has been logged, and returns the whole log.
81 async fn wait_for_mail(dir: &Path, marker: &str) -> String {71 async fn wait_for_mail(dir: &Path, marker: &str) -> String {
82 for _ in 0..200 {72 for _ in 0..200 {
83 let log = mail_log(dir);73 let log = mail_log(dir);
@@ -89,13 +79,11 @@ async fn wait_for_mail(dir: &Path, marker: &str) -> String {
89 panic!("no mail with {marker} was logged");79 panic!("no mail with {marker} was logged");
90 }80 }
91 81
92-/// The `/reset/<token>` path from the first reset mail in the log.
93 fn reset_path(log: &str) -> String {82 fn reset_path(log: &str) -> String {
94 let start = log.find("/reset/").expect("reset link");83 let start = log.find("/reset/").expect("reset link");
95 log[start..].split_whitespace().next().unwrap().to_owned()84 log[start..].split_whitespace().next().unwrap().to_owned()
96 }85 }
97 86
98-/// Logs in with `username` and `password`. Returns the HTTP status of the attempt.
99 async fn login_status(http: &Http, username: &str, password: &str) -> u16 {87 async fn login_status(http: &Http, username: &str, password: &str) -> u16 {
100 let page = http.get("/login", None).await;88 let page = http.get("/login", None).await;
101 let cookie = cookie_named(&page, "__Host-forge_precsrf").expect("precsrf cookie");89 let cookie = cookie_named(&page, "__Host-forge_precsrf").expect("precsrf cookie");
@@ -115,7 +103,6 @@ async fn login_status(http: &Http, username: &str, password: &str) -> u16 {
115 res.status103 res.status
116 }104 }
117 105
118-/// Submits the forgot form for `email` and returns the answer's status and body.
119 async fn forgot(http: &Http, email: &str) -> Resp {106 async fn forgot(http: &Http, email: &str) -> Resp {
120 let page = http.get("/forgot", None).await;107 let page = http.get("/forgot", None).await;
121 assert_eq!(page.status, 200, "GET /forgot");108 assert_eq!(page.status, 200, "GET /forgot");
@@ -171,7 +158,6 @@ async fn reset_link_sets_a_new_password_once() {
171 "new password works"158 "new password works"
172 );159 );
173 160
174- // Reusing the link is refused, and the password does not change again.
175 let again = http.post_form(&path, &form, Some(&cookie)).await;161 let again = http.post_form(&path, &form, Some(&cookie)).await;
176 assert_eq!(again.status, 200);162 assert_eq!(again.status, 200);
177 assert!(again.body.contains("This reset link is invalid"));163 assert!(again.body.contains("This reset link is invalid"));
@@ -196,7 +182,6 @@ async fn an_unverified_address_gets_no_reset_mail_and_the_same_answer() {
196 unverified.body.contains("is on its way")182 unverified.body.contains("is on its way")
197 );183 );
198 184
199- // Give the background lookups time to run, then confirm nothing was sent.
200 tokio::time::sleep(Duration::from_secs(1)).await;185 tokio::time::sleep(Duration::from_secs(1)).await;
201 assert!(!mail_log(&dir).contains("/reset/"), "no reset mail for bob");186 assert!(!mail_log(&dir).contains("/reset/"), "no reset mail for bob");
202 }187 }
crates/forge-e2e/tests/e2e/advisories_e2e.rsmodified+0 -22
@@ -1,13 +1,3 @@
1-//! End-to-end: security advisories against one real `forge` binary. The OSV dump is a zip built by
2-//! the test and placed where the worker expects it, fresh, so the worker never downloads anything.
3-//! A repo's `Cargo.lock` is pushed over smart HTTP, the default-branch push scans it, and the
4-//! security page shows the alert.
5-//!
6-//! Scenarios:
7-//! - the alert opens after a push that locks a vulnerable version;
8-//! - an owner dismisses it, reopens it, and a fixing push moves it to `fixed`;
9-//! - a reader without Write gets a 404 on the page.
10-
11 use crate::common::{1 use crate::common::{
12 Http, Resp, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path,2 Http, Resp, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path,
13 write_config_with,3 write_config_with,
@@ -23,7 +13,6 @@ const BOB_PW: &str = "bob-password-123";
23 const ADVISORIES_TOML: &str = "\n[advisories]\nenabled = true\necosystems = [\"crates.io\"]\n";13 const ADVISORIES_TOML: &str = "\n[advisories]\nenabled = true\necosystems = [\"crates.io\"]\n";
24 const SCAN_TIMEOUT: Duration = Duration::from_secs(30);14 const SCAN_TIMEOUT: Duration = Duration::from_secs(30);
25 15
26-/// An OSV record: `demo` before 2.0.0 is affected.
27 const OSV_RECORD: &str = r#"{16 const OSV_RECORD: &str = r#"{
28 "id": "RUSTSEC-TEST-0001",17 "id": "RUSTSEC-TEST-0001",
29 "summary": "demo is vulnerable before 2.0.0",18 "summary": "demo is vulnerable before 2.0.0",
@@ -38,7 +27,6 @@ const OSV_RECORD: &str = r#"{
38 const LOCK_OLD: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n";27 const LOCK_OLD: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n";
39 const LOCK_FIXED: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"2.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n";28 const LOCK_FIXED: &str = "version = 4\n\n[[package]]\nname = \"demo\"\nversion = \"2.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n";
40 29
41-/// Runs git with credential helpers disabled. Panics on failure and returns trimmed stdout.
42 fn git(cwd: &Path, args: &[&str]) -> String {30 fn git(cwd: &Path, args: &[&str]) -> String {
43 let out: Output = Command::new("git")31 let out: Output = Command::new("git")
44 .current_dir(cwd)32 .current_dir(cwd)
@@ -59,7 +47,6 @@ fn git(cwd: &Path, args: &[&str]) -> String {
59 String::from_utf8_lossy(&out.stdout).trim().to_owned()47 String::from_utf8_lossy(&out.stdout).trim().to_owned()
60 }48 }
61 49
62-/// Writes `Cargo.lock` with `contents`, commits it, and returns the new HEAD.
63 fn commit_lock(repo: &Path, contents: &str, message: &str) -> String {50 fn commit_lock(repo: &Path, contents: &str, message: &str) -> String {
64 fs::write(repo.join("Cargo.lock"), contents).expect("write Cargo.lock");51 fs::write(repo.join("Cargo.lock"), contents).expect("write Cargo.lock");
65 git(repo, &["add", "Cargo.lock"]);52 git(repo, &["add", "Cargo.lock"]);
@@ -70,7 +57,6 @@ fn commit_lock(repo: &Path, contents: &str, message: &str) -> String {
70 git(repo, &["rev-parse", "HEAD"])57 git(repo, &["rev-parse", "HEAD"])
71 }58 }
72 59
73-/// A dump zip holding the one OSV record, as `all.zip` holds them.
74 fn dump_zip() -> Vec<u8> {60 fn dump_zip() -> Vec<u8> {
75 let mut buf = Cursor::new(Vec::new());61 let mut buf = Cursor::new(Vec::new());
76 {62 {
@@ -96,13 +82,11 @@ async fn boot() -> Booted {
96 if !tool_on_path("git") {82 if !tool_on_path("git") {
97 panic!("`git` was not found on PATH");83 panic!("`git` was not found on PATH");
98 }84 }
99- // Keep the path short: the internal unix socket path is limited to 108 bytes.
100 let root = tempfile::Builder::new()85 let root = tempfile::Builder::new()
101 .prefix("adv2e")86 .prefix("adv2e")
102 .tempdir_in("/tmp")87 .tempdir_in("/tmp")
103 .expect("temp dir");88 .expect("temp dir");
104 let dir = root.path().to_path_buf();89 let dir = root.path().to_path_buf();
105- // The dump is written before the server starts, so it is fresh and never downloaded.
106 let dump_dir = dir.join("advisories").join("crates.io");90 let dump_dir = dir.join("advisories").join("crates.io");
107 fs::create_dir_all(&dump_dir).expect("dump dir");91 fs::create_dir_all(&dump_dir).expect("dump dir");
108 fs::write(dump_dir.join("all.zip"), dump_zip()).expect("write dump");92 fs::write(dump_dir.join("all.zip"), dump_zip()).expect("write dump");
@@ -168,12 +152,10 @@ async fn new_repo(http: &Http, session: &str, name: &str) {
168 assert_eq!(res.status, 303, "create repo {name}: {}", res.body);152 assert_eq!(res.status, 303, "create repo {name}: {}", res.body);
169 }153 }
170 154
171-/// The security page as `session` sees it. Returns the status and body.
172 async fn security_page(http: &Http, session: &str) -> Resp {155 async fn security_page(http: &Http, session: &str) -> Resp {
173 http.get_cookie("/tahinli/app/security", session).await156 http.get_cookie("/tahinli/app/security", session).await
174 }157 }
175 158
176-/// Polls the security page until `text` shows up, or fails after `SCAN_TIMEOUT`.
177 async fn wait_for_text(http: &Http, session: &str, text: &str) -> String {159 async fn wait_for_text(http: &Http, session: &str, text: &str) -> String {
178 let deadline = Instant::now() + SCAN_TIMEOUT;160 let deadline = Instant::now() + SCAN_TIMEOUT;
179 loop {161 loop {
@@ -190,7 +172,6 @@ async fn wait_for_text(http: &Http, session: &str, text: &str) -> String {
190 }172 }
191 }173 }
192 174
193-/// Posts the dismiss or reopen form for the single alert on the page.
194 async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp {175 async fn post_alert_action(http: &Http, session: &str, action: &str) -> Resp {
195 let page = security_page(http, session).await;176 let page = security_page(http, session).await;
196 assert_eq!(page.status, 200, "GET security page");177 assert_eq!(page.status, 200, "GET security page");
@@ -228,12 +209,10 @@ async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() {
228 commit_lock(&work, LOCK_OLD, "lock demo 1.0.0");209 commit_lock(&work, LOCK_OLD, "lock demo 1.0.0");
229 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);210 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
230 211
231- // The push scans the lockfile in the background.
232 let page = wait_for_text(&b.http, &tahinli, "RUSTSEC-TEST-0001").await;212 let page = wait_for_text(&b.http, &tahinli, "RUSTSEC-TEST-0001").await;
233 assert!(page.contains(">Open</span>"), "the alert is open");213 assert!(page.contains(">Open</span>"), "the alert is open");
234 assert!(page.contains("demo"), "the vulnerable package is listed");214 assert!(page.contains("demo"), "the vulnerable package is listed");
235 215
236- // Dismiss, then reopen. The reader without Write is refused.
237 let dismissed = post_alert_action(&b.http, &tahinli, "dismiss").await;216 let dismissed = post_alert_action(&b.http, &tahinli, "dismiss").await;
238 assert_eq!(dismissed.status, 303, "dismiss: {}", dismissed.body);217 assert_eq!(dismissed.status, 303, "dismiss: {}", dismissed.body);
239 let page = wait_for_text(&b.http, &tahinli, ">Dismissed</span>").await;218 let page = wait_for_text(&b.http, &tahinli, ">Dismissed</span>").await;
@@ -247,7 +226,6 @@ async fn advisory_alert_opens_on_push_and_follows_dismiss_reopen_and_fix() {
247 let refused = security_page(&b.http, &bob).await;226 let refused = security_page(&b.http, &bob).await;
248 assert_eq!(refused.status, 404, "a reader without Write gets 404");227 assert_eq!(refused.status, 404, "a reader without Write gets 404");
249 228
250- // A push that locks the fixed version closes the alert.
251 commit_lock(&work, LOCK_FIXED, "lock demo 2.0.0");229 commit_lock(&work, LOCK_FIXED, "lock demo 2.0.0");
252 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);230 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
253 wait_for_text(&b.http, &tahinli, ">Fixed</span>").await;231 wait_for_text(&b.http, &tahinli, ">Fixed</span>").await;
crates/forge-e2e/tests/e2e/branch_protection_e2e.rsmodified+0 -20
@@ -1,7 +1,3 @@
1-//! End-to-end checks for branch protection in the pre-receive hook. It starts the real `forge`
2-//! binary, pushes with the real `git` client over HTTPS, and writes rules through `forge-core`
3-//! while the server runs. Helpers mirror `git_e2e.rs`.
4-
5 use crate::common::{1 use crate::common::{
6 Http, Ports, Server, describe, input_value, launch, login, pick_ports, relaunch, run_admin,2 Http, Ports, Server, describe, input_value, launch, login, pick_ports, relaunch, run_admin,
7 tool_on_path, write_config,3 tool_on_path, write_config,
@@ -18,7 +14,6 @@ fn ok(out: &Output, what: &str) {
18 assert!(out.status.success(), "{what} failed:\n{}", describe(out));14 assert!(out.status.success(), "{what} failed:\n{}", describe(out));
19 }15 }
20 16
21-/// Asserts failure and returns the combined output for further checks.
22 fn rejected(out: &Output, what: &str) -> String {17 fn rejected(out: &Output, what: &str) -> String {
23 assert!(18 assert!(
24 !out.status.success(),19 !out.status.success(),
@@ -53,7 +48,6 @@ fn set_identity(repo: &Path) {
53 );48 );
54 }49 }
55 50
56-/// Writes a file, commits it in `repo`, and returns the new HEAD.
57 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) -> String {51 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) -> String {
58 fs::write(repo.join(name), content).expect("write file");52 fs::write(repo.join(name), content).expect("write file");
59 set_identity(repo);53 set_identity(repo);
@@ -74,7 +68,6 @@ fn head_sha(repo: &Path) -> String {
74 String::from_utf8_lossy(&out.stdout).trim().to_owned()68 String::from_utf8_lossy(&out.stdout).trim().to_owned()
75 }69 }
76 70
77-/// The commit a remote ref points at, as reported by `git ls-remote`.
78 fn remote_sha(repo: &Path, reference: &str) -> String {71 fn remote_sha(repo: &Path, reference: &str) -> String {
79 let out = git(repo, &["ls-remote", "origin", reference]);72 let out = git(repo, &["ls-remote", "origin", reference]);
80 ok(&out, "ls-remote");73 ok(&out, "ls-remote");
@@ -85,7 +78,6 @@ fn remote_sha(repo: &Path, reference: &str) -> String {
85 .to_owned()78 .to_owned()
86 }79 }
87 80
88-/// Creates an access token through `/settings/tokens` and returns the token shown once.
89 async fn create_token(http: &Http, session: &str, name: &str) -> String {81 async fn create_token(http: &Http, session: &str, name: &str) -> String {
90 let page = http.get_cookie("/settings/keys", session).await;82 let page = http.get_cookie("/settings/keys", session).await;
91 assert_eq!(page.status, 200, "GET /settings/keys");83 assert_eq!(page.status, 200, "GET /settings/keys");
@@ -135,7 +127,6 @@ async fn create_repo(http: &Http, session: &str, name: &str) {
135 );127 );
136 }128 }
137 129
138-/// Paths and handles shared by the steps of the test.
139 struct Ctx {130 struct Ctx {
140 dir: PathBuf,131 dir: PathBuf,
141 config: PathBuf,132 config: PathBuf,
@@ -144,14 +135,10 @@ struct Ctx {
144 ports: Ports,135 ports: Ports,
145 }136 }
146 137
147-/// Starts the server again on the ports the first launch settled on.
148 async fn start_server(ctx: &Ctx) -> Server {138 async fn start_server(ctx: &Ctx) -> Server {
149 relaunch(&ctx.config, &ctx.log, ctx.ports).await139 relaunch(&ctx.config, &ctx.log, ctx.ports).await
150 }140 }
151 141
152-/// Stops the server, writes one rule through `forge-core`, and starts the server again. The
153-/// database file is locked while the server runs, so the rule cannot be written in place. The
154-/// hook reads the rules on every push, so a restart changes nothing else.
155 async fn set_rule(142 async fn set_rule(
156 ctx: &Ctx,143 ctx: &Ctx,
157 server: Server,144 server: Server,
@@ -184,7 +171,6 @@ async fn branch_protection_end_to_end() {
184 return;171 return;
185 }172 }
186 173
187- // Keep the path short: the internal unix socket path is limited to 108 bytes.
188 let root = tempfile::Builder::new()174 let root = tempfile::Builder::new()
189 .prefix("fbp")175 .prefix("fbp")
190 .tempdir_in("/tmp")176 .tempdir_in("/tmp")
@@ -206,7 +192,6 @@ async fn branch_protection_end_to_end() {
206 let token = create_token(&ctx.http, &tahinli, "bp-token").await;192 let token = create_token(&ctx.http, &tahinli, "bp-token").await;
207 create_repo(&ctx.http, &tahinli, "bp").await;193 create_repo(&ctx.http, &tahinli, "bp").await;
208 194
209- // Look up the repo id while the server is stopped, since the database is locked otherwise.
210 drop(server);195 drop(server);
211 let repo_id = {196 let repo_id = {
212 let store = Store::open(&ctx.dir.join("forge.db"))197 let store = Store::open(&ctx.dir.join("forge.db"))
@@ -240,11 +225,9 @@ async fn branch_protection_end_to_end() {
240 "push release/1",225 "push release/1",
241 );226 );
242 227
243- // Divergent history on main: c3 is not a descendant of c2.
244 ok(&git(&work, &["reset", "-q", "--hard", &c1]), "reset");228 ok(&git(&work, &["reset", "-q", "--hard", &c1]), "reset");
245 let c3 = commit_file(&work, "file.txt", "three\n", "three");229 let c3 = commit_file(&work, "file.txt", "three\n", "three");
246 230
247- // 1. Default protection: force-push to main is rejected.
248 let force = git(&work, &["push", "-f", "origin", "HEAD:main"]);231 let force = git(&work, &["push", "-f", "origin", "HEAD:main"]);
249 let text = rejected(&force, "force-push to default branch");232 let text = rejected(&force, "force-push to default branch");
250 assert!(233 assert!(
@@ -253,7 +236,6 @@ async fn branch_protection_end_to_end() {
253 );236 );
254 assert_eq!(remote_sha(&work, "refs/heads/main"), c2);237 assert_eq!(remote_sha(&work, "refs/heads/main"), c2);
255 238
256- // 2. A rule that allows force pushes lets the force-push through, but not deletion.
257 server = set_rule(&ctx, server, &repo_id, "main", true, false).await;239 server = set_rule(&ctx, server, &repo_id, "main", true, false).await;
258 ok(240 ok(
259 &git(&work, &["push", "-f", "origin", "HEAD:main"]),241 &git(&work, &["push", "-f", "origin", "HEAD:main"]),
@@ -269,7 +251,6 @@ async fn branch_protection_end_to_end() {
269 );251 );
270 assert_eq!(remote_sha(&work, "refs/heads/main"), c3);252 assert_eq!(remote_sha(&work, "refs/heads/main"), c3);
271 253
272- // 3. A release/* rule without force pushes rejects release/1 but not feature/x (no rule).
273 server = set_rule(&ctx, server, &repo_id, "release/*", false, true).await;254 server = set_rule(&ctx, server, &repo_id, "release/*", false, true).await;
274 ok(&git(&work, &["reset", "-q", "--hard", &c1]), "reset");255 ok(&git(&work, &["reset", "-q", "--hard", &c1]), "reset");
275 let c4 = commit_file(&work, "file.txt", "four\n", "four");256 let c4 = commit_file(&work, "file.txt", "four\n", "four");
@@ -294,7 +275,6 @@ async fn branch_protection_end_to_end() {
294 );275 );
295 assert_eq!(remote_sha(&work, "refs/heads/feature/x"), c4);276 assert_eq!(remote_sha(&work, "refs/heads/feature/x"), c4);
296 277
297- // 4. Deleting a non-default branch with no rule succeeds.
298 ok(278 ok(
299 &git(&work, &["push", "origin", "--delete", "feature/x"]),279 &git(&work, &["push", "origin", "--delete", "feature/x"]),
300 "delete unprotected feature/x",280 "delete unprotected feature/x",
crates/forge-e2e/tests/e2e/browse_e2e.rsmodified+0 -28
@@ -1,10 +1,3 @@
1-//! Black-box browse test. It starts the real `forge` binary with three listeners (app, ssh and
2-//! the raw user-content origin), pushes fixtures over HTTPS with a token, and checks the app pages
3-//! and the raw origin with plain HTTP.
4-//!
5-//! Cookies are handled by hand, as in `git_e2e.rs`: the session cookie is `__Host-forge_session`
6-//! with `Secure`, so a cookie jar would not send it over plain http.
7-
8 use crate::common::{boot_admin, describe, input_value, tool_on_path};1 use crate::common::{boot_admin, describe, input_value, tool_on_path};
9 use std::fs;2 use std::fs;
10 use std::path::Path;3 use std::path::Path;
@@ -19,7 +12,6 @@ use reqwest::header::{
19 const TAHINLI_PW: &str = "tahinli-password-123";12 const TAHINLI_PW: &str = "tahinli-password-123";
20 const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x00IEND\xaeB`\x82";13 const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x00IEND\xaeB`\x82";
21 14
22-/// A received HTTP response. The body is kept as bytes because the archive is binary.
23 struct Resp {15 struct Resp {
24 status: u16,16 status: u16,
25 headers: HeaderMap,17 headers: HeaderMap,
@@ -47,7 +39,6 @@ impl Resp {
47 }39 }
48 }40 }
49 41
50-/// A client for one listener. `base` is the origin, e.g. `http://127.0.0.1:8080`.
51 struct Http {42 struct Http {
52 client: reqwest::Client,43 client: reqwest::Client,
53 base: String,44 base: String,
@@ -96,8 +87,6 @@ impl Http {
96 }87 }
97 }88 }
98 89
99-/// Returns `name=value` for the cookie whose name ends with `suffix`, e.g. `forge_session`
100-/// matches `__Host-forge_session`. Cleared cookies (empty value) are ignored.
101 fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {90 fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {
102 resp.set_cookies().iter().find_map(|set| {91 resp.set_cookies().iter().find_map(|set| {
103 let pair = set.split(';').next()?;92 let pair = set.split(';').next()?;
@@ -106,7 +95,6 @@ fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {
106 })95 })
107 }96 }
108 97
109-/// The values of `attr` on every element matching `selector`, in document order.
110 fn attr_values(body: &str, selector: &str, attr: &str) -> Vec<String> {98 fn attr_values(body: &str, selector: &str, attr: &str) -> Vec<String> {
111 let doc = scraper::Html::parse_document(body);99 let doc = scraper::Html::parse_document(body);
112 let selector = scraper::Selector::parse(selector).expect("selector");100 let selector = scraper::Selector::parse(selector).expect("selector");
@@ -115,7 +103,6 @@ fn attr_values(body: &str, selector: &str, attr: &str) -> Vec<String> {
115 .collect()103 .collect()
116 }104 }
117 105
118-/// The text of every element matching `selector`.
119 fn element_texts(body: &str, selector: &str) -> Vec<String> {106 fn element_texts(body: &str, selector: &str) -> Vec<String> {
120 let doc = scraper::Html::parse_document(body);107 let doc = scraper::Html::parse_document(body);
121 let selector = scraper::Selector::parse(selector).expect("selector");108 let selector = scraper::Selector::parse(selector).expect("selector");
@@ -124,8 +111,6 @@ fn element_texts(body: &str, selector: &str) -> Vec<String> {
124 .collect()111 .collect()
125 }112 }
126 113
127-/// Checks the latest commit in a repo page's head line: its short sha linking to the commit, no
128-/// subject, and the commit count label.
129 fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &str) {114 fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &str) {
130 assert_eq!(115 assert_eq!(
131 element_texts(body, ".head-sub").len(),116 element_texts(body, ".head-sub").len(),
@@ -176,8 +161,6 @@ fn set_identity(repo: &Path) {
176 );161 );
177 }162 }
178 163
179-/// Writes the browse fixtures into `work`: a README with a heading, a relative link and a relative
180-/// image, a Rust source file, a PNG, and an HTML file that must never render inline.
181 fn write_fixtures(work: &Path) {164 fn write_fixtures(work: &Path) {
182 fs::create_dir_all(work.join("src")).expect("create src");165 fs::create_dir_all(work.join("src")).expect("create src");
183 fs::write(166 fs::write(
@@ -195,7 +178,6 @@ fn write_fixtures(work: &Path) {
195 .expect("write weights.bin");178 .expect("write weights.bin");
196 }179 }
197 180
198-/// Stages everything in `repo` and commits it with the repo's local identity.
199 fn commit_all(repo: &Path, message: &str) {181 fn commit_all(repo: &Path, message: &str) {
200 set_identity(repo);182 set_identity(repo);
201 ok(&git(repo, &["add", "-A"]), "git add");183 ok(&git(repo, &["add", "-A"]), "git add");
@@ -214,8 +196,6 @@ fn head_sha(repo: &Path) -> String {
214 String::from_utf8_lossy(&out.stdout).trim().to_owned()196 String::from_utf8_lossy(&out.stdout).trim().to_owned()
215 }197 }
216 198
217-/// Clones the empty repo at `url` into `work`, pushes the fixtures to `main` and an extra commit to
218-/// `feature/x`, and returns the commit oid of `main`.
219 fn push_fixtures(dir: &Path, url: &str, work: &Path) -> String {199 fn push_fixtures(dir: &Path, url: &str, work: &Path) -> String {
220 ok(&git(dir, &["clone", url, path_str(work)]), "https clone");200 ok(&git(dir, &["clone", url, path_str(work)]), "https clone");
221 write_fixtures(work);201 write_fixtures(work);
@@ -236,7 +216,6 @@ fn push_fixtures(dir: &Path, url: &str, work: &Path) -> String {
236 main_oid216 main_oid
237 }217 }
238 218
239-/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header.
240 async fn login(http: &Http, username: &str, password: &str) -> String {219 async fn login(http: &Http, username: &str, password: &str) -> String {
241 let page = http.get("/login", None).await;220 let page = http.get("/login", None).await;
242 assert_eq!(page.status, 200, "GET /login");221 assert_eq!(page.status, 200, "GET /login");
@@ -258,7 +237,6 @@ async fn login(http: &Http, username: &str, password: &str) -> String {
258 cookie_named(&res, "forge_session").expect("session cookie after login")237 cookie_named(&res, "forge_session").expect("session cookie after login")
259 }238 }
260 239
261-/// Creates an access token through `/settings/tokens` and returns the token shown once.
262 async fn create_token(http: &Http, session: &str, name: &str) -> String {240 async fn create_token(http: &Http, session: &str, name: &str) -> String {
263 let page = http.get("/settings/keys", Some(session)).await;241 let page = http.get("/settings/keys", Some(session)).await;
264 assert_eq!(page.status, 200, "GET /settings/keys");242 assert_eq!(page.status, 200, "GET /settings/keys");
@@ -280,7 +258,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String {
280 token258 token
281 }259 }
282 260
283-/// Creates a repo through `/new`.
284 async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {261 async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {
285 let page = http.get("/new", Some(session)).await;262 let page = http.get("/new", Some(session)).await;
286 assert_eq!(page.status, 200, "GET /new");263 assert_eq!(page.status, 200, "GET /new");
@@ -305,7 +282,6 @@ async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {
305 );282 );
306 }283 }
307 284
308-/// Asserts that a response on the raw origin sets no cookie.
309 fn assert_no_cookie(resp: &Resp, what: &str) {285 fn assert_no_cookie(resp: &Resp, what: &str) {
310 assert!(286 assert!(
311 resp.set_cookies().is_empty(),287 resp.set_cookies().is_empty(),
@@ -580,7 +556,6 @@ async fn browse_end_to_end() {
580 assert_no_cookie(&login_page, "raw /login");556 assert_no_cookie(&login_page, "raw /login");
581 }557 }
582 558
583-/// Opens a code view stream and returns the response with its body still unread.
584 async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {559 async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {
585 let mut req = http.client.get(format!("{}{path}", http.base));560 let mut req = http.client.get(format!("{}{path}", http.base));
586 if let Some(cookie) = cookie {561 if let Some(cookie) = cookie {
@@ -594,7 +569,6 @@ async fn open_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::
594 res569 res
595 }570 }
596 571
597-/// The next chunk of a stream. None when nothing arrives within two seconds.
598 async fn next_chunk(res: &mut reqwest::Response) -> Option<String> {572 async fn next_chunk(res: &mut reqwest::Response) -> Option<String> {
599 let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk())573 let chunk = tokio::time::timeout(Duration::from_secs(2), res.chunk())
600 .await574 .await
@@ -715,7 +689,6 @@ async fn code_view_stream_follows_pushes() {
715 );689 );
716 }690 }
717 691
718-/// Reads the next event of `stream` and checks it is a `changed` event for `what`.
719 async fn assert_changed(stream: &mut reqwest::Response, what: &str) {692 async fn assert_changed(stream: &mut reqwest::Response, what: &str) {
720 let event = next_chunk(stream)693 let event = next_chunk(stream)
721 .await694 .await
@@ -723,7 +696,6 @@ async fn assert_changed(stream: &mut reqwest::Response, what: &str) {
723 assert!(event.contains("event: changed"), "{what}: {event}");696 assert!(event.contains("event: changed"), "{what}: {event}");
724 }697 }
725 698
726-/// Posts a form that must succeed with a redirect.
727 async fn post_redirect(http: &Http, path: &str, form: &[(&str, &str)], session: &str) {699 async fn post_redirect(http: &Http, path: &str, form: &[(&str, &str)], session: &str) {
728 let res = http.post_form(path, form, Some(session)).await;700 let res = http.post_form(path, form, Some(session)).await;
729 assert_eq!(res.status, 303, "POST {path}: {}", res.body());701 assert_eq!(res.status, 303, "POST {path}: {}", res.body());
crates/forge-e2e/tests/e2e/ci_e2e.rsmodified+0 -57
@@ -1,15 +1,3 @@
1-//! End-to-end: CI against the real `forge` binary, driven by the real `forge-runner` library.
2-//!
3-//! The runner side uses `HostExecutor` (behind the `test-host-executor` feature), so jobs run as
4-//! plain `sh` on the test host. Everything else is the production path: runner registration over
5-//! the HTTP API, claims, the job's git fetch over smart HTTP with its job token, log shipping with
6-//! masking, artifact upload, and finish.
7-//!
8-//! Scenarios:
9-//! - a push run: secrets are masked in the log, artifacts download, a failure skips dependants;
10-//! - a fork pull request: it waits for approval, then runs without secrets;
11-//! - a live log: `log.txt` streams while a job runs and ends when the job finishes.
12-
13 use crate::common::{1 use crate::common::{
14 FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, run_admin, write_config,2 FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, run_admin, write_config,
15 };3 };
@@ -33,7 +21,6 @@ const REPO_PATH: &str = "/tahinli/r";
33 const SECRET_VALUE: &str = "supersecretvalue";21 const SECRET_VALUE: &str = "supersecretvalue";
34 const LABELS: &[&str] = &["linux"];22 const LABELS: &[&str] = &["linux"];
35 23
36-/// The push-triggered workflow. Image strings are ignored by `HostExecutor`.
37 const CI_TOML: &str = r#"[on]24 const CI_TOML: &str = r#"[on]
38 push = ["main"]25 push = ["main"]
39 pull_request = true26 pull_request = true
@@ -61,8 +48,6 @@ run = "echo never"
61 needs = ["broken"]48 needs = ["broken"]
62 "#;49 "#;
63 50
64-/// The same workflow with the build line changed to print the secret in a form that stays
65-/// readable when the variable is unset. Bob's pull request uses it, so `set -u` does not abort.
66 const CI_TOML_FORK: &str = r#"[on]51 const CI_TOML_FORK: &str = r#"[on]
67 push = ["main"]52 push = ["main"]
68 pull_request = true53 pull_request = true
@@ -90,7 +75,6 @@ run = "echo never"
90 needs = ["broken"]75 needs = ["broken"]
91 "#;76 "#;
92 77
93-/// The text of the first element matching `selector`.
94 fn first_text(body: &str, selector: &str) -> String {78 fn first_text(body: &str, selector: &str) -> String {
95 let doc = scraper::Html::parse_document(body);79 let doc = scraper::Html::parse_document(body);
96 let selector = scraper::Selector::parse(selector).expect("selector");80 let selector = scraper::Selector::parse(selector).expect("selector");
@@ -103,7 +87,6 @@ fn first_text(body: &str, selector: &str) -> String {
103 .to_owned()87 .to_owned()
104 }88 }
105 89
106-/// Runs git in `cwd` with `env` applied on top of the inherited environment. Returns stdout.
107 fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {90 fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {
108 let mut cmd = Command::new("git");91 let mut cmd = Command::new("git");
109 cmd.current_dir(cwd)92 cmd.current_dir(cwd)
@@ -126,8 +109,6 @@ fn git(cwd: &Path, args: &[&str]) -> String {
126 git_env(cwd, args, &[])109 git_env(cwd, args, &[])
127 }110 }
128 111
129-/// Writes `file` (creating its directory), commits it with `who` as author and committer, and
130-/// returns the new HEAD.
131 fn commit(112 fn commit(
132 repo: &Path,113 repo: &Path,
133 file: &str,114 file: &str,
@@ -155,7 +136,6 @@ fn commit(
155 git(repo, &["rev-parse", "HEAD"])136 git(repo, &["rev-parse", "HEAD"])
156 }137 }
157 138
158-/// Clones `url` into `into` (a path that does not exist yet) and returns it.
159 fn clone(url: &str, into: &Path) -> PathBuf {139 fn clone(url: &str, into: &Path) -> PathBuf {
160 let parent = into.parent().expect("clone target has a parent");140 let parent = into.parent().expect("clone target has a parent");
161 git(141 git(
@@ -165,19 +145,16 @@ fn clone(url: &str, into: &Path) -> PathBuf {
165 into.to_path_buf()145 into.to_path_buf()
166 }146 }
167 147
168-/// The HTTPS remote for `owner/repo`, authenticated with a token.
169 fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {148 fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
170 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")149 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
171 }150 }
172 151
173-/// The CSRF token shown on any settings page of the signed-in user.
174 async fn csrf_from(http: &Http, path: &str, session: &str) -> String {152 async fn csrf_from(http: &Http, path: &str, session: &str) -> String {
175 let page = http.get(path, Some(session)).await;153 let page = http.get(path, Some(session)).await;
176 assert_eq!(page.status, 200, "GET {path}");154 assert_eq!(page.status, 200, "GET {path}");
177 input_value(&page.body, "csrf")155 input_value(&page.body, "csrf")
178 }156 }
179 157
180-/// Creates an access token through `/settings/tokens` and returns the token shown once.
181 async fn create_token(http: &Http, session: &str, name: &str) -> String {158 async fn create_token(http: &Http, session: &str, name: &str) -> String {
182 let csrf = csrf_from(http, "/settings/keys", session).await;159 let csrf = csrf_from(http, "/settings/keys", session).await;
183 let res = http160 let res = http
@@ -193,7 +170,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String {
193 token170 token
194 }171 }
195 172
196-/// Creates a public repo `name` owned by tahinli through `/new`.
197 async fn create_repo(http: &Http, session: &str, name: &str) {173 async fn create_repo(http: &Http, session: &str, name: &str) {
198 let page = http.get("/new", Some(session)).await;174 let page = http.get("/new", Some(session)).await;
199 assert_eq!(page.status, 200, "GET /new");175 assert_eq!(page.status, 200, "GET /new");
@@ -218,7 +194,6 @@ async fn create_repo(http: &Http, session: &str, name: &str) {
218 );194 );
219 }195 }
220 196
221-/// Adds or replaces a repo secret through the settings form.
222 async fn set_secret(http: &Http, session: &str, name: &str, value: &str) {197 async fn set_secret(http: &Http, session: &str, name: &str, value: &str) {
223 let csrf = csrf_from(http, &format!("{REPO_PATH}/settings/secrets"), session).await;198 let csrf = csrf_from(http, &format!("{REPO_PATH}/settings/secrets"), session).await;
224 let res = http199 let res = http
@@ -231,8 +206,6 @@ async fn set_secret(http: &Http, session: &str, name: &str, value: &str) {
231 assert_eq!(res.status, 303, "set secret {name}: {}", res.body);206 assert_eq!(res.status, 303, "set secret {name}: {}", res.body);
232 }207 }
233 208
234-/// A running server with its own temp data dir. Field order matters: the server is dropped (and
235-/// killed) before the temp dir is removed.
236 struct Booted {209 struct Booted {
237 _server: Server,210 _server: Server,
238 _root: tempfile::TempDir,211 _root: tempfile::TempDir,
@@ -242,14 +215,11 @@ struct Booted {
242 port: u16,215 port: u16,
243 }216 }
244 217
245-/// The server's log, for assertion messages.
246 fn server_log(b: &Booted) -> String {218 fn server_log(b: &Booted) -> String {
247 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()219 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
248 }220 }
249 221
250-/// Creates tahinli (admin) and bob, then boots the server on fresh ports.
251 async fn boot() -> Booted {222 async fn boot() -> Booted {
252- // Keep the path short: the internal unix socket path is limited to 108 bytes.
253 let root = tempfile::Builder::new()223 let root = tempfile::Builder::new()
254 .prefix("ci2e")224 .prefix("ci2e")
255 .tempdir_in("/tmp")225 .tempdir_in("/tmp")
@@ -271,7 +241,6 @@ async fn boot() -> Booted {
271 }241 }
272 }242 }
273 243
274-/// A registered runner and the secret it claims with.
275 struct Worker {244 struct Worker {
276 runner: Runner,245 runner: Runner,
277 secret: String,246 secret: String,
@@ -279,7 +248,6 @@ struct Worker {
279 }248 }
280 249
281 impl Worker {250 impl Worker {
282- /// One claim. `None` means the forge had nothing for this runner (after its long poll).
283 async fn claim(&self) -> Option<JobAssignment> {251 async fn claim(&self) -> Option<JobAssignment> {
284 self.runner252 self.runner
285 .client()253 .client()
@@ -289,7 +257,6 @@ impl Worker {
289 .job257 .job
290 }258 }
291 259
292- /// Claims and runs jobs until the forge has nothing left. Returns how many ran.
293 async fn drain(&self) -> usize {260 async fn drain(&self) -> usize {
294 let mut ran = 0;261 let mut ran = 0;
295 while let Some(job) = self.claim().await {262 while let Some(job) = self.claim().await {
@@ -300,7 +267,6 @@ impl Worker {
300 }267 }
301 }268 }
302 269
303-/// Registers a runner through the admin page and the runner API. The admin is `admin_session`.
304 async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {270 async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {
305 let page = b.http.get("/admin/runners", Some(admin_session)).await;271 let page = b.http.get("/admin/runners", Some(admin_session)).await;
306 assert_eq!(page.status, 200, "GET /admin/runners");272 assert_eq!(page.status, 200, "GET /admin/runners");
@@ -338,7 +304,6 @@ async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker
338 images: forge_runner::config::ImagesConfig::default(),304 images: forge_runner::config::ImagesConfig::default(),
339 sandbox: forge_runner::config::SandboxConfig::default(),305 sandbox: forge_runner::config::SandboxConfig::default(),
340 registries: Vec::new(),306 registries: Vec::new(),
341- // The e2e runner must not replace the test binary under itself.
342 auto_update: false,307 auto_update: false,
343 cache_max_gib: 0,308 cache_max_gib: 0,
344 };309 };
@@ -351,7 +316,6 @@ async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker
351 }316 }
352 }317 }
353 318
354-/// One commit status as the status API reports it.
355 #[derive(Debug, Clone)]319 #[derive(Debug, Clone)]
356 struct Status {320 struct Status {
357 state: String,321 state: String,
@@ -359,7 +323,6 @@ struct Status {
359 target_url: String,323 target_url: String,
360 }324 }
361 325
362-/// The statuses on `sha` of tahinli/r, keyed by context.
363 async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap<String, Status> {326 async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap<String, Status> {
364 let res = http327 let res = http
365 .get_bearer(328 .get_bearer(
@@ -387,7 +350,6 @@ async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap<String, Statu
387 .collect()350 .collect()
388 }351 }
389 352
390-/// Polls the statuses until every context in `contexts` is present, then returns them.
391 async fn wait_statuses(353 async fn wait_statuses(
392 http: &Http,354 http: &Http,
393 token: &str,355 token: &str,
@@ -408,7 +370,6 @@ async fn wait_statuses(
408 }370 }
409 }371 }
410 372
411-/// The job id at the end of a status `target_url` (`.../ci/jobs/<id>`).
412 fn job_id_of(status: &Status) -> String {373 fn job_id_of(status: &Status) -> String {
413 status374 status
414 .target_url375 .target_url
@@ -419,7 +380,6 @@ fn job_id_of(status: &Status) -> String {
419 .to_owned()380 .to_owned()
420 }381 }
421 382
422-/// Pushes `.forge/ci.toml` (with `contents`) to `main` as tahinli. Returns the pushed commit.
423 fn push_ci_config(work: &Path, contents: &str) -> String {383 fn push_ci_config(work: &Path, contents: &str) -> String {
424 let sha = commit(384 let sha = commit(
425 work,385 work,
@@ -467,7 +427,6 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
467 assert_eq!(found["ci/skipme"].state, "error");427 assert_eq!(found["ci/skipme"].state, "error");
468 assert_eq!(found["ci/skipme"].description, "skipped");428 assert_eq!(found["ci/skipme"].description, "skipped");
469 429
470- // The build log: the secret is masked, never printed.
471 let build_id = job_id_of(&found["ci/build"]);430 let build_id = job_id_of(&found["ci/build"]);
472 let log = b431 let log = b
473 .http432 .http
@@ -482,7 +441,6 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
482 log.body441 log.body
483 );442 );
484 443
485- // The artifact comes back with the right bytes. `out/a.txt` is stored as `out_a.txt`.
486 let artifact = b444 let artifact = b
487 .http445 .http
488 .get(446 .get(
@@ -493,7 +451,6 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
493 assert_eq!(artifact.status, 200, "GET artifact: {}", server_log(&b));451 assert_eq!(artifact.status, 200, "GET artifact: {}", server_log(&b));
494 assert_eq!(artifact.body, "data\n", "artifact bytes");452 assert_eq!(artifact.body, "data\n", "artifact bytes");
495 453
496- // The run page lists every job.
497 let run = b454 let run = b
498 .http455 .http
499 .get(&format!("{REPO_PATH}/ci/runs/1"), Some(&tahinli))456 .get(&format!("{REPO_PATH}/ci/runs/1"), Some(&tahinli))
@@ -502,8 +459,6 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
502 for job in ["build", "after", "broken", "skipme"] {459 for job in ["build", "after", "broken", "skipme"] {
503 assert!(run.body.contains(job), "run page lists {job}");460 assert!(run.body.contains(job), "run page lists {job}");
504 }461 }
505- // The timeline draws what a job needs as connectors, not as a line under its name: muted from
506- // build into after, in the accent from the failed broken onto the skipped skipme.
507 assert!(462 assert!(
508 run.body.contains(r#"class="ci-glink" data-rel="j"#),463 run.body.contains(r#"class="ci-glink" data-rel="j"#),
509 "build links to after: {}",464 "build links to after: {}",
@@ -535,7 +490,6 @@ async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() {
535 create_repo(&b.http, &tahinli, "r").await;490 create_repo(&b.http, &tahinli, "r").await;
536 let worker = register_runner(&b, &tahinli, "runner-a").await;491 let worker = register_runner(&b, &tahinli, "runner-a").await;
537 492
538- // Each `::group::` line the job prints is one of its steps.
539 let work = clone(493 let work = clone(
540 &remote(b.port, "tahinli", &token, "tahinli", "r"),494 &remote(b.port, "tahinli", &token, "tahinli", "r"),
541 &b.dir.join("tahinli-work"),495 &b.dir.join("tahinli-work"),
@@ -590,7 +544,6 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
590 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;544 set_secret(&b.http, &tahinli, "MY_SECRET", SECRET_VALUE).await;
591 let worker = register_runner(&b, &tahinli, "runner-a").await;545 let worker = register_runner(&b, &tahinli, "runner-a").await;
592 546
593- // Base branch with the workflow, run to completion (run 1).
594 let work = clone(547 let work = clone(
595 &remote(b.port, "tahinli", &token, "tahinli", "r"),548 &remote(b.port, "tahinli", &token, "tahinli", "r"),
596 &b.dir.join("tahinli-work"),549 &b.dir.join("tahinli-work"),
@@ -599,7 +552,6 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
599 wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await;552 wait_statuses(&b.http, &token, &base_sha, &["ci/build"]).await;
600 worker.drain().await;553 worker.drain().await;
601 554
602- // Bob forks and changes the workflow on a branch.
603 let bob = login(&b.http, "bob", BOB_PW).await;555 let bob = login(&b.http, "bob", BOB_PW).await;
604 let bob_token = create_token(&b.http, &bob, "bob-token").await;556 let bob_token = create_token(&b.http, &bob, "bob-token").await;
605 let csrf = csrf_from(&b.http, "/settings/keys", &bob).await;557 let csrf = csrf_from(&b.http, "/settings/keys", &bob).await;
@@ -627,7 +579,6 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
627 &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"],579 &["push", "-q", "origin", "HEAD:refs/heads/bob-feature"],
628 );580 );
629 581
630- // Bob opens the pull request. The run waits for the owner.
631 let compare = b582 let compare = b
632 .http583 .http
633 .get(584 .get(
@@ -668,7 +619,6 @@ async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
668 run_page.body619 run_page.body
669 );620 );
670 621
671- // The owner approves, and the job runs with no secrets.
672 let approve = b622 let approve = b
673 .http623 .http
674 .post_form(624 .post_form(
@@ -707,8 +657,6 @@ async fn live_log_streams_until_the_job_finishes() {
707 create_repo(&b.http, &tahinli, "r").await;657 create_repo(&b.http, &tahinli, "r").await;
708 let worker = register_runner(&b, &tahinli, "runner-a").await;658 let worker = register_runner(&b, &tahinli, "runner-a").await;
709 659
710- // The job holds until the test drops a release file, so the first line is seen while it runs.
711- // The loop is capped, so a test that dies early does not leave the job spinning.
712 let release = b.dir.join("release");660 let release = b.dir.join("release");
713 let slow = format!(661 let slow = format!(
714 r#"[on]662 r#"[on]
@@ -733,7 +681,6 @@ run = "echo started; i=0; while [ ! -f {} ] && [ $i -lt 100 ]; do sleep 0.1; i=$
733 let runner = worker.runner.clone();681 let runner = worker.runner.clone();
734 let handle = tokio::spawn(async move { runner.process(job, CancellationToken::new()).await });682 let handle = tokio::spawn(async move { runner.process(job, CancellationToken::new()).await });
735 683
736- // Read the stream chunk by chunk. The first line appears while the job is still sleeping.
737 let url = format!("{}{REPO_PATH}/ci/jobs/{job_id}/log.txt", b.http.base);684 let url = format!("{}{REPO_PATH}/ci/jobs/{job_id}/log.txt", b.http.base);
738 let mut res = b.http.client.get(url).send().await.expect("GET log.txt");685 let mut res = b.http.client.get(url).send().await.expect("GET log.txt");
739 assert_eq!(res.status().as_u16(), 200, "GET log.txt");686 assert_eq!(res.status().as_u16(), 200, "GET log.txt");
@@ -775,7 +722,6 @@ async fn ci_job_token_clones_the_repos_wiki_read_only() {
775 create_repo(&b.http, &tahinli, "r").await;722 create_repo(&b.http, &tahinli, "r").await;
776 let worker = register_runner(&b, &tahinli, "runner-a").await;723 let worker = register_runner(&b, &tahinli, "runner-a").await;
777 724
778- // The wiki gets its first page through the web form.
779 let csrf = input_value(725 let csrf = input_value(
780 &b.http726 &b.http
781 .get(&format!("{REPO_PATH}/wiki/-/new"), Some(&tahinli))727 .get(&format!("{REPO_PATH}/wiki/-/new"), Some(&tahinli))
@@ -799,7 +745,6 @@ async fn ci_job_token_clones_the_repos_wiki_read_only() {
799 .await;745 .await;
800 assert_eq!(saved.status, 303, "create Home: {}", saved.body);746 assert_eq!(saved.status, 303, "create Home: {}", saved.body);
801 747
802- // A slow job keeps running, so its token is valid while the test clones.
803 let slow = r#"[on]748 let slow = r#"[on]
804 push = ["main"]749 push = ["main"]
805 750
@@ -816,7 +761,6 @@ run = "echo started; sleep 5; echo done"
816 let job = worker.claim().await.expect("the slow job is claimed");761 let job = worker.claim().await.expect("the slow job is claimed");
817 assert_eq!(job.job_id, job_id_of(&found["ci/slow"]));762 assert_eq!(job.job_id, job_id_of(&found["ci/slow"]));
818 763
819- // The job reads the wiki with its own credential: `ci-job` and `<job id>:<job token>`.
820 let wiki_url = format!(764 let wiki_url = format!(
821 "http://ci-job:{}:{}@127.0.0.1:{}/tahinli/r.wiki.git",765 "http://ci-job:{}:{}@127.0.0.1:{}/tahinli/r.wiki.git",
822 job.job_id, job.job_token, b.port766 job.job_id, job.job_token, b.port
@@ -825,7 +769,6 @@ run = "echo started; sleep 5; echo done"
825 let home = fs::read_to_string(job_wiki.join("Home.md")).expect("Home.md in the job's clone");769 let home = fs::read_to_string(job_wiki.join("Home.md")).expect("Home.md in the job's clone");
826 assert!(home.contains("Welcome from the wiki"), "{home}");770 assert!(home.contains("Welcome from the wiki"), "{home}");
827 771
828- // Pushing to the wiki is refused for a job token.
829 fs::write(job_wiki.join("Home.md"), "# changed by a job\n").expect("write");772 fs::write(job_wiki.join("Home.md"), "# changed by a job\n").expect("write");
830 git(&job_wiki, &["add", "Home.md"]);773 git(&job_wiki, &["add", "Home.md"]);
831 git_env(774 git_env(
crates/forge-e2e/tests/e2e/common/http.rsmodified+0 -17
@@ -1,14 +1,9 @@
1-//! The HTTP client the e2e tests use against a running `forge serve`. A request can carry a
2-//! cookie or a bearer or basic credential, and a response keeps its status, headers and body
3-//! text. The login flow every test starts with lives here too.
4-
5 use std::time::Duration;1 use std::time::Duration;
6 2
7 use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE};3 use reqwest::header::{COOKIE, HeaderMap, HeaderName, LOCATION, SET_COOKIE};
8 4
9 use super::input_value;5 use super::input_value;
10 6
11-/// A received response. Headers are kept whole, so a test can read any of them.
12 pub struct Resp {7 pub struct Resp {
13 pub status: u16,8 pub status: u16,
14 pub headers: HeaderMap,9 pub headers: HeaderMap,
@@ -16,7 +11,6 @@ pub struct Resp {
16 }11 }
17 12
18 impl Resp {13 impl Resp {
19- /// The first value of a header, when it is valid text.
20 pub fn header(&self, name: HeaderName) -> Option<String> {14 pub fn header(&self, name: HeaderName) -> Option<String> {
21 self.headers15 self.headers
22 .get(name)16 .get(name)
@@ -24,12 +18,10 @@ impl Resp {
24 .map(str::to_owned)18 .map(str::to_owned)
25 }19 }
26 20
27- /// The `Location` header, when there is one.
28 pub fn location(&self) -> Option<String> {21 pub fn location(&self) -> Option<String> {
29 self.header(LOCATION)22 self.header(LOCATION)
30 }23 }
31 24
32- /// Every `Set-Cookie` value, in the order the server sent them. Cleared cookies included.
33 pub fn set_cookies(&self) -> Vec<String> {25 pub fn set_cookies(&self) -> Vec<String> {
34 self.headers26 self.headers
35 .get_all(SET_COOKIE)27 .get_all(SET_COOKIE)
@@ -39,7 +31,6 @@ impl Resp {
39 }31 }
40 }32 }
41 33
42-/// A client bound to one listener. It never follows redirects.
43 pub struct Http {34 pub struct Http {
44 pub client: reqwest::Client,35 pub client: reqwest::Client,
45 pub base: String,36 pub base: String,
@@ -50,7 +41,6 @@ impl Http {
50 Self::with_base(format!("http://127.0.0.1:{port}"))41 Self::with_base(format!("http://127.0.0.1:{port}"))
51 }42 }
52 43
53- /// A client for an explicit base URL, such as a listener reached through another host name.
54 pub fn with_base(base: String) -> Self {44 pub fn with_base(base: String) -> Self {
55 let client = reqwest::Client::builder()45 let client = reqwest::Client::builder()
56 .redirect(reqwest::redirect::Policy::none())46 .redirect(reqwest::redirect::Policy::none())
@@ -64,7 +54,6 @@ impl Http {
64 self.get_language(path, cookie, None).await54 self.get_language(path, cookie, None).await
65 }55 }
66 56
67- /// `get` with an optional `Accept-Language` value.
68 pub async fn get_language(57 pub async fn get_language(
69 &self,58 &self,
70 path: &str,59 path: &str,
@@ -78,7 +67,6 @@ impl Http {
78 self.send(req, cookie).await67 self.send(req, cookie).await
79 }68 }
80 69
81- /// `get` with the cookie header set to `cookie` exactly, even when it is empty.
82 pub async fn get_cookie(&self, path: &str, cookie: &str) -> Resp {70 pub async fn get_cookie(&self, path: &str, cookie: &str) -> Resp {
83 self.get(path, Some(cookie)).await71 self.get(path, Some(cookie)).await
84 }72 }
@@ -107,8 +95,6 @@ impl Http {
107 .await95 .await
108 }96 }
109 97
110- /// Opens a live stream as `cookie`, or anonymously. A stream that opens sends its `retry`
111- /// field first, which is read here, not treated as an event.
112 pub async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response {98 pub async fn stream(&self, path: &str, cookie: Option<&str>) -> reqwest::Response {
113 let mut req = self.client.get(format!("{}{path}", self.base));99 let mut req = self.client.get(format!("{}{path}", self.base));
114 if let Some(cookie) = cookie {100 if let Some(cookie) = cookie {
@@ -126,7 +112,6 @@ impl Http {
126 res112 res
127 }113 }
128 114
129- /// Sends a prepared request, with `cookie` as its Cookie header when there is one.
130 pub async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp {115 pub async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp {
131 let req = match cookie {116 let req = match cookie {
132 Some(cookie) => req.header(COOKIE, cookie),117 Some(cookie) => req.header(COOKIE, cookie),
@@ -144,7 +129,6 @@ impl Http {
144 }129 }
145 }130 }
146 131
147-/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored.
148 pub fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {132 pub fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {
149 resp.set_cookies().iter().find_map(|set| {133 resp.set_cookies().iter().find_map(|set| {
150 let pair = set.split(';').next()?;134 let pair = set.split(';').next()?;
@@ -158,7 +142,6 @@ pub fn with_cookie(session: &str, res: &Resp, notice: &str) -> String {
158 format!("{session}; {cookie}")142 format!("{session}; {cookie}")
159 }143 }
160 144
161-/// Signs in as `username` through the `/login` form and returns the session cookie.
162 pub async fn login(http: &Http, username: &str, password: &str) -> String {145 pub async fn login(http: &Http, username: &str, password: &str) -> String {
163 let page = http.get("/login", None).await;146 let page = http.get("/login", None).await;
164 assert_eq!(page.status, 200, "GET /login");147 assert_eq!(page.status, 200, "GET /login");
crates/forge-e2e/tests/e2e/common/mod.rsmodified+0 -42
@@ -1,11 +1,3 @@
1-//! Helpers shared by the forge-web e2e tests. `main.rs` declares this module once, and each test
2-//! module imports what it needs from `crate::common`.
3-//!
4-//! The server is started with `launch`, which waits for the three listeners (HTTP, user content
5-//! and SSH) with backoff. A connection that is refused just means "not yet". If the child exits
6-//! first, the panic carries its captured log. A port picked with `pick_ports` is only free until
7-//! the server binds it, so `launch` retries on fresh ports when the server reports a bind conflict.
8-
9 use std::fs;1 use std::fs;
10 use std::net::TcpStream;2 use std::net::TcpStream;
11 use std::path::{Path, PathBuf};3 use std::path::{Path, PathBuf};
@@ -19,10 +11,6 @@ mod http;
19 11
20 pub use http::{Http, Resp, cookie_named, login, with_cookie};12 pub use http::{Http, Resp, cookie_named, login, with_cookie};
21 13
22-/// The forge binary the tests start. `env!("CARGO_BIN_EXE_forge")` would only work in the package
23-/// that owns the binary, and these tests live in `forge-e2e`, which does not depend on forge-web.
24-/// CI sets `FORGE_BIN` to the prebuilt release binary. Without it, the dev-profile binary is built
25-/// once per test run, so `cargo test --workspace` works with no extra steps.
26 pub fn bin() -> &'static str {14 pub fn bin() -> &'static str {
27 static BIN: OnceLock<String> = OnceLock::new();15 static BIN: OnceLock<String> = OnceLock::new();
28 BIN.get_or_init(|| match std::env::var("FORGE_BIN") {16 BIN.get_or_init(|| match std::env::var("FORGE_BIN") {
@@ -32,7 +20,6 @@ pub fn bin() -> &'static str {
32 .as_str()20 .as_str()
33 }21 }
34 22
35-/// Builds `forge` with cargo and returns the executable path cargo reports for it.
36 fn build_forge() -> String {23 fn build_forge() -> String {
37 let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned());24 let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned());
38 let output = Command::new(&cargo)25 let output = Command::new(&cargo)
@@ -62,12 +49,9 @@ fn build_forge() -> String {
62 .unwrap_or_else(|| panic!("cargo build reported no executable for the forge binary"))49 .unwrap_or_else(|| panic!("cargo build reported no executable for the forge binary"))
63 }50 }
64 51
65-/// How long a freshly spawned server gets to answer on all three listeners.
66 const READY_TIMEOUT: Duration = Duration::from_secs(30);52 const READY_TIMEOUT: Duration = Duration::from_secs(30);
67-/// Starts `forge serve` on fresh ports at most this many times after bind conflicts.
68 const MAX_LAUNCH_ATTEMPTS: u32 = 5;53 const MAX_LAUNCH_ATTEMPTS: u32 = 5;
69 54
70-/// The running `forge serve` child. Killed on drop, even when an assertion fails.
71 pub struct Server(pub Child);55 pub struct Server(pub Child);
72 56
73 impl Drop for Server {57 impl Drop for Server {
@@ -77,7 +61,6 @@ impl Drop for Server {
77 }61 }
78 }62 }
79 63
80-/// The three loopback ports a server listens on: the app, SSH and the raw user-content listener.
81 #[derive(Clone, Copy, Debug, PartialEq, Eq)]64 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
82 pub struct Ports {65 pub struct Ports {
83 pub http: u16,66 pub http: u16,
@@ -85,7 +68,6 @@ pub struct Ports {
85 pub content: u16,68 pub content: u16,
86 }69 }
87 70
88-/// The value of the named `<input>` on a page, read with an HTML parser.
89 pub fn input_value(body: &str, name: &str) -> String {71 pub fn input_value(body: &str, name: &str) -> String {
90 let doc = scraper::Html::parse_document(body);72 let doc = scraper::Html::parse_document(body);
91 let selector = scraper::Selector::parse(&format!("input[name=\"{name}\"]")).expect("selector");73 let selector = scraper::Selector::parse(&format!("input[name=\"{name}\"]")).expect("selector");
@@ -103,7 +85,6 @@ pub fn temp_dir(prefix: &str) -> tempfile::TempDir {
103 .expect("temp dir")85 .expect("temp dir")
104 }86 }
105 87
106-/// A port the kernel handed out for a moment. It is free only until something binds it.
107 pub fn free_port() -> u16 {88 pub fn free_port() -> u16 {
108 std::net::TcpListener::bind("127.0.0.1:0")89 std::net::TcpListener::bind("127.0.0.1:0")
109 .expect("bind free port")90 .expect("bind free port")
@@ -112,7 +93,6 @@ pub fn free_port() -> u16 {
112 .port()93 .port()
113 }94 }
114 95
115-/// Three distinct free ports.
116 pub fn pick_ports() -> Ports {96 pub fn pick_ports() -> Ports {
117 let mut ports: Vec<u16> = Vec::new();97 let mut ports: Vec<u16> = Vec::new();
118 while ports.len() < 3 {98 while ports.len() < 3 {
@@ -137,13 +117,10 @@ pub fn tool_on_path(name: &str) -> bool {
137 .is_ok()117 .is_ok()
138 }118 }
139 119
140-/// Writes `dir/forge.toml` for `ports` and returns its path.
141 pub fn write_config(dir: &Path, ports: Ports) -> PathBuf {120 pub fn write_config(dir: &Path, ports: Ports) -> PathBuf {
142 write_config_with(dir, ports, "")121 write_config_with(dir, ports, "")
143 }122 }
144 123
145-/// Like `write_config`, with `extra` TOML appended after the defaults (for example a `[webhooks]`
146-/// table). `extra` must not repeat a key or table the defaults already set.
147 pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf {124 pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf {
148 let d = dir.display();125 let d = dir.display();
149 let Ports {126 let Ports {
@@ -169,8 +146,6 @@ pub fn write_config_with(dir: &Path, ports: Ports, extra: &str) -> PathBuf {
169 path146 path
170 }147 }
171 148
172-/// `[ci]` settings for tests that drain the queue. A claim that finds nothing waits `claim_wait_ms`
173-/// before it answers 204, and the production default is 25 s, so the test server answers at once.
174 pub const FAST_CLAIMS: &str = "[ci]\nclaim_wait_ms = 50\n";149 pub const FAST_CLAIMS: &str = "[ci]\nclaim_wait_ms = 50\n";
175 150
176 pub fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {151 pub fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
@@ -185,7 +160,6 @@ pub fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
185 cmd.output().expect("run git")160 cmd.output().expect("run git")
186 }161 }
187 162
188-/// Creates an access token through `/settings/tokens` and returns the token shown once.
189 pub async fn create_token(http: &Http, session: &str, name: &str) -> String {163 pub async fn create_token(http: &Http, session: &str, name: &str) -> String {
190 let page = http.get_cookie("/settings/keys", session).await;164 let page = http.get_cookie("/settings/keys", session).await;
191 assert_eq!(page.status, 200, "GET /settings/keys");165 assert_eq!(page.status, 200, "GET /settings/keys");
@@ -211,7 +185,6 @@ pub async fn create_token(http: &Http, session: &str, name: &str) -> String {
211 token185 token
212 }186 }
213 187
214-/// Creates a repo through `/new`.
215 pub async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {188 pub async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {
216 let page = http.get_cookie("/new", session).await;189 let page = http.get_cookie("/new", session).await;
217 assert_eq!(page.status, 200, "GET /new");190 assert_eq!(page.status, 200, "GET /new");
@@ -274,7 +247,6 @@ pub fn describe(out: &Output) -> String {
274 )247 )
275 }248 }
276 249
277-/// Waits for the next event of a stream, which must be `changed`.
278 pub async fn next_changed(res: &mut reqwest::Response, what: &str) {250 pub async fn next_changed(res: &mut reqwest::Response, what: &str) {
279 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())251 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
280 .await252 .await
@@ -301,8 +273,6 @@ pub fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str)
301 );273 );
302 }274 }
303 275
304-/// A fresh server with `tahinli` as its only user, an admin. The temp dir is under `/tmp` so the
305-/// socket paths stay under the 108-byte unix limit. Returns the dir, the server and its ports.
306 pub async fn boot_admin(prefix: &str, password: &str) -> (TempDir, Server, Ports) {276 pub async fn boot_admin(prefix: &str, password: &str) -> (TempDir, Server, Ports) {
307 let root = tempfile::Builder::new()277 let root = tempfile::Builder::new()
308 .prefix(prefix)278 .prefix(prefix)
@@ -315,16 +285,10 @@ pub async fn boot_admin(prefix: &str, password: &str) -> (TempDir, Server, Ports
315 (root, server, ports)285 (root, server, ports)
316 }286 }
317 287
318-/// Starts `forge serve` on `ports` and returns once all three listeners answer. The config is
319-/// written to `dir/forge.toml` and the log to `dir/serve.log`.
320-///
321-/// If the server exits because one of the ports was taken in the meantime, it is started again on
322-/// fresh ports. The ports in use are returned, so callers must build their clients from them.
323 pub async fn launch(dir: &Path, ports: Ports) -> (Server, Ports) {288 pub async fn launch(dir: &Path, ports: Ports) -> (Server, Ports) {
324 launch_with(dir, ports, "").await289 launch_with(dir, ports, "").await
325 }290 }
326 291
327-/// `launch` with extra TOML appended to the config (see `write_config_with`).
328 pub async fn launch_with(dir: &Path, ports: Ports, extra: &str) -> (Server, Ports) {292 pub async fn launch_with(dir: &Path, ports: Ports, extra: &str) -> (Server, Ports) {
329 let log_path = dir.join("serve.log");293 let log_path = dir.join("serve.log");
330 let mut ports = ports;294 let mut ports = ports;
@@ -346,8 +310,6 @@ pub async fn launch_with(dir: &Path, ports: Ports, extra: &str) -> (Server, Port
346 unreachable!("the last attempt either returns or panics")310 unreachable!("the last attempt either returns or panics")
347 }311 }
348 312
349-/// Starts the server again on the exact `ports` of an earlier run, for restart tests. Unlike
350-/// `launch` this does not retry, because the caller's clients already use these ports.
351 pub async fn relaunch(config: &Path, log_path: &Path, ports: Ports) -> Server {313 pub async fn relaunch(config: &Path, log_path: &Path, ports: Ports) -> Server {
352 let mut server = spawn(config, log_path);314 let mut server = spawn(config, log_path);
353 match wait_ready(ports, &mut server, log_path).await {315 match wait_ready(ports, &mut server, log_path).await {
@@ -373,8 +335,6 @@ fn spawn(config: &Path, log_path: &Path) -> Server {
373 Server(child)335 Server(child)
374 }336 }
375 337
376-/// Polls the three listeners with backoff until they all answer. Returns the exit status if the
377-/// child dies first, and panics with the log if the deadline passes.
378 async fn wait_ready(ports: Ports, server: &mut Server, log: &Path) -> Result<(), ExitStatus> {338 async fn wait_ready(ports: Ports, server: &mut Server, log: &Path) -> Result<(), ExitStatus> {
379 let client = reqwest::Client::builder()339 let client = reqwest::Client::builder()
380 .timeout(Duration::from_secs(2))340 .timeout(Duration::from_secs(2))
@@ -402,7 +362,6 @@ async fn wait_ready(ports: Ports, server: &mut Server, log: &Path) -> Result<(),
402 }362 }
403 }363 }
404 364
405-/// True when the URL answers 200. Connection refused, timeouts and other errors all mean "not yet".
406 async fn probe(client: &reqwest::Client, url: &str) -> bool {365 async fn probe(client: &reqwest::Client, url: &str) -> bool {
407 matches!(client.get(url).send().await, Ok(res) if res.status() == reqwest::StatusCode::OK)366 matches!(client.get(url).send().await, Ok(res) if res.status() == reqwest::StatusCode::OK)
408 }367 }
@@ -415,7 +374,6 @@ fn read_log(log: &Path) -> String {
415 fs::read_to_string(log).unwrap_or_default()374 fs::read_to_string(log).unwrap_or_default()
416 }375 }
417 376
418-/// Whether the server log reports that a listener could not bind because the port is taken.
419 fn bind_conflict(log: &str) -> bool {377 fn bind_conflict(log: &str) -> bool {
420 let log = log.to_ascii_lowercase();378 let log = log.to_ascii_lowercase();
421 log.contains("address already in use")379 log.contains("address already in use")
crates/forge-e2e/tests/e2e/community_i18n_e2e.rsmodified+0 -4
@@ -1,6 +1,3 @@
1-//! End-to-end check that a community page (snippets) follows the viewer's browser language:
2-//! Turkish when `Accept-Language` asks for it, English otherwise.
3-
4 use std::process::Command;1 use std::process::Command;
5 use std::time::Duration;2 use std::time::Duration;
6 3
@@ -9,7 +6,6 @@ use reqwest::header::ACCEPT_LANGUAGE;
9 6
10 const PW: &str = "tahinli-password-123";7 const PW: &str = "tahinli-password-123";
11 8
12-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
13 fn admin(config: &std::path::Path, args: &[&str]) {9 fn admin(config: &std::path::Path, args: &[&str]) {
14 let out = Command::new(bin())10 let out = Command::new(bin())
15 .arg("--config")11 .arg("--config")
crates/forge-e2e/tests/e2e/discussions_e2e.rsmodified+0 -15
@@ -1,8 +1,3 @@
1-//! End-to-end: discussions over HTTP against a running server. Covers the settings toggle that
2-//! shows and hides the tab, creating a discussion, a reply and a nested reply (refused), marking
3-//! an answer in Q&A, and the lock: once locked, a plain viewer's comment is refused while the
4-//! owner can still write.
5-
6 use crate::common::{1 use crate::common::{
7 Http, input_value, launch, login, pick_ports, run_admin, tool_on_path, write_config,2 Http, input_value, launch, login, pick_ports, run_admin, tool_on_path, write_config,
8 };3 };
@@ -10,7 +5,6 @@ use crate::common::{
10 const TAHINLI_PW: &str = "tahinli-password-123";5 const TAHINLI_PW: &str = "tahinli-password-123";
11 const BOB_PW: &str = "bob-password-4567";6 const BOB_PW: &str = "bob-password-4567";
12 7
13-/// Creates a public repo through `/new`.
14 async fn create_repo(http: &Http, session: &str, name: &str) {8 async fn create_repo(http: &Http, session: &str, name: &str) {
15 let page = http.get("/new", Some(session)).await;9 let page = http.get("/new", Some(session)).await;
16 assert_eq!(page.status, 200, "GET /new");10 assert_eq!(page.status, 200, "GET /new");
@@ -35,7 +29,6 @@ async fn create_repo(http: &Http, session: &str, name: &str) {
35 );29 );
36 }30 }
37 31
38-/// The `#comment-<id>` anchor of a redirect location, as the id.
39 fn anchored_id(location: Option<&str>) -> String {32 fn anchored_id(location: Option<&str>) -> String {
40 location33 location
41 .and_then(|l| l.rsplit_once("#comment-"))34 .and_then(|l| l.rsplit_once("#comment-"))
@@ -64,7 +57,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
64 let bob = login(&http, "bob", BOB_PW).await;57 let bob = login(&http, "bob", BOB_PW).await;
65 create_repo(&http, &tahinli, "pub").await;58 create_repo(&http, &tahinli, "pub").await;
66 59
67- // Off by default: the tab is absent and the pages do not exist.
68 let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await;60 let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await;
69 assert_eq!(repo_page.status, 200);61 assert_eq!(repo_page.status, 200);
70 assert!(62 assert!(
@@ -79,7 +71,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
79 "list while off"71 "list while off"
80 );72 );
81 73
82- // Turn them on from settings, as the owner.
83 let settings = http74 let settings = http
84 .get("/tahinli/pub/settings", Some(tahinli.as_str()))75 .get("/tahinli/pub/settings", Some(tahinli.as_str()))
85 .await;76 .await;
@@ -99,7 +90,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
99 "the Discussions tab is missing after turning it on"90 "the Discussions tab is missing after turning it on"
100 );91 );
101 92
102- // Tahinli opens a Q&A discussion.
103 let form = http93 let form = http
104 .get("/tahinli/pub/discussions/new", Some(tahinli.as_str()))94 .get("/tahinli/pub/discussions/new", Some(tahinli.as_str()))
105 .await;95 .await;
@@ -124,7 +114,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
124 );114 );
125 let discussion = "/tahinli/pub/discussions/1";115 let discussion = "/tahinli/pub/discussions/1";
126 116
127- // Bob answers at the top level, then replies to that comment.
128 let page = http.get(discussion, Some(bob.as_str())).await;117 let page = http.get(discussion, Some(bob.as_str())).await;
129 assert_eq!(page.status, 200, "GET discussion as bob");118 assert_eq!(page.status, 200, "GET discussion as bob");
130 let csrf_bob = input_value(&page.body, "csrf");119 let csrf_bob = input_value(&page.body, "csrf");
@@ -152,7 +141,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
152 assert_eq!(res.status, 303, "reply: {}", res.body);141 assert_eq!(res.status, 303, "reply: {}", res.body);
153 let reply = anchored_id(res.location().as_deref());142 let reply = anchored_id(res.location().as_deref());
154 143
155- // A reply to a reply is refused, and the page says why.
156 let res = http144 let res = http
157 .post_form(145 .post_form(
158 &format!("{discussion}/comments"),146 &format!("{discussion}/comments"),
@@ -171,7 +159,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
171 res.body159 res.body
172 );160 );
173 161
174- // Tahinli (the author) marks the top comment as the answer.
175 let page = http.get(discussion, Some(tahinli.as_str())).await;162 let page = http.get(discussion, Some(tahinli.as_str())).await;
176 let csrf_tahinli = input_value(&page.body, "csrf");163 let csrf_tahinli = input_value(&page.body, "csrf");
177 let res = http164 let res = http
@@ -192,7 +179,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
192 "the answered badge is missing after marking an answer"179 "the answered badge is missing after marking an answer"
193 );180 );
194 181
195- // Tahinli locks the conversation. Bob can no longer comment, and cannot lock it either.
196 let page = http.get(discussion, Some(tahinli.as_str())).await;182 let page = http.get(discussion, Some(tahinli.as_str())).await;
197 let csrf_tahinli = input_value(&page.body, "csrf");183 let csrf_tahinli = input_value(&page.body, "csrf");
198 let res = http184 let res = http
@@ -220,7 +206,6 @@ async fn discussions_create_reply_answer_lock_and_toggle() {
220 .await;206 .await;
221 assert_eq!(res.status, 403, "bob locks a discussion");207 assert_eq!(res.status, 403, "bob locks a discussion");
222 208
223- // Turning discussions off hides the tab and the pages.
224 let settings = http209 let settings = http
225 .get("/tahinli/pub/settings", Some(tahinli.as_str()))210 .get("/tahinli/pub/settings", Some(tahinli.as_str()))
226 .await;211 .await;
crates/forge-e2e/tests/e2e/git_e2e.rsmodified+0 -33
@@ -1,9 +1,3 @@
1-//! Black-box end-to-end test. It starts the real `forge` binary and drives it with the real
2-//! `git` and `ssh` clients over smart HTTP and SSH, plus raw HTTP requests for the negative cases.
3-//!
4-//! Cookies are handled by hand: the session cookie is `__Host-forge_session` with `Secure`, so a
5-//! cookie jar would not send it over plain http. The test parses `Set-Cookie` and sends `Cookie`.
6-
7 use crate::common::{1 use crate::common::{
8 Http, create_repo, create_token, describe, git, input_value, launch, login, pick_ports,2 Http, create_repo, create_token, describe, git, input_value, launch, login, pick_ports,
9 run_admin, tool_on_path, write_config,3 run_admin, tool_on_path, write_config,
@@ -21,7 +15,6 @@ fn ok(out: &Output, what: &str) {
21 assert!(out.status.success(), "{what} failed:\n{}", describe(out));15 assert!(out.status.success(), "{what} failed:\n{}", describe(out));
22 }16 }
23 17
24-/// Asserts failure and returns the combined output for further checks.
25 fn rejected(out: &Output, what: &str) -> String {18 fn rejected(out: &Output, what: &str) -> String {
26 assert!(19 assert!(
27 !out.status.success(),20 !out.status.success(),
@@ -35,8 +28,6 @@ fn path_str(path: &Path) -> &str {
35 path.to_str().expect("utf-8 path")28 path.to_str().expect("utf-8 path")
36 }29 }
37 30
38-/// The ssh command git runs for SSH remotes. Host key checks are off because the host key is
39-/// new on every run.
40 fn ssh_opts(key: &Path, ssh_port: u16) -> Vec<String> {31 fn ssh_opts(key: &Path, ssh_port: u16) -> Vec<String> {
41 [32 [
42 "-i",33 "-i",
@@ -83,7 +74,6 @@ fn set_identity(repo: &Path) {
83 );74 );
84 }75 }
85 76
86-/// Writes a file and commits it in `repo` with the repo's local identity.
87 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {77 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {
88 fs::write(repo.join(name), content).expect("write file");78 fs::write(repo.join(name), content).expect("write file");
89 set_identity(repo);79 set_identity(repo);
@@ -104,7 +94,6 @@ fn head_sha(repo: &Path) -> String {
104 String::from_utf8_lossy(&out.stdout).trim().to_owned()94 String::from_utf8_lossy(&out.stdout).trim().to_owned()
105 }95 }
106 96
107-/// True when a file called `name` exists anywhere under `dir`.
108 fn find_file(dir: &Path, name: &str) -> bool {97 fn find_file(dir: &Path, name: &str) -> bool {
109 std::fs::read_dir(dir).is_ok_and(|entries| {98 std::fs::read_dir(dir).is_ok_and(|entries| {
110 entries.flatten().any(|entry| {99 entries.flatten().any(|entry| {
@@ -117,7 +106,6 @@ fn read(path: PathBuf) -> String {
117 fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))106 fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()))
118 }107 }
119 108
120-/// Adds a public key through `/settings/keys`.
121 async fn add_key(http: &Http, session: &str, public_key: &str) {109 async fn add_key(http: &Http, session: &str, public_key: &str) {
122 let page = http.get_cookie("/settings/keys", session).await;110 let page = http.get_cookie("/settings/keys", session).await;
123 assert_eq!(page.status, 200, "GET /settings/keys");111 assert_eq!(page.status, 200, "GET /settings/keys");
@@ -147,7 +135,6 @@ async fn git_end_to_end() {
147 }135 }
148 }136 }
149 137
150- // Keep the path short: the internal unix socket path is limited to 108 bytes.
151 let root = tempfile::Builder::new()138 let root = tempfile::Builder::new()
152 .prefix("fe2e")139 .prefix("fe2e")
153 .tempdir_in("/tmp")140 .tempdir_in("/tmp")
@@ -163,7 +150,6 @@ async fn git_end_to_end() {
163 let http = Http::new(ports.http);150 let http = Http::new(ports.http);
164 let (http_port, ssh_port) = (ports.http, ports.ssh);151 let (http_port, ssh_port) = (ports.http, ports.ssh);
165 152
166- // Web setup: tahinli logs in, makes a token, adds an SSH key and creates both repos.
167 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;153 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
168 let tahinli_token = create_token(&http, &tahinli, "e2e-token").await;154 let tahinli_token = create_token(&http, &tahinli, "e2e-token").await;
169 155
@@ -175,7 +161,6 @@ async fn git_end_to_end() {
175 create_repo(&http, &tahinli, "pub", "public").await;161 create_repo(&http, &tahinli, "pub", "public").await;
176 create_repo(&http, &tahinli, "priv", "private").await;162 create_repo(&http, &tahinli, "priv", "private").await;
177 163
178- // HTTPS: push to the public repo with the token, then read it back.
179 let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git");164 let pub_url = format!("http://tahinli:{tahinli_token}@127.0.0.1:{http_port}/tahinli/pub.git");
180 let pub_work = dir.join("pub-work");165 let pub_work = dir.join("pub-work");
181 ok(166 ok(
@@ -196,7 +181,6 @@ async fn git_end_to_end() {
196 );181 );
197 assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n");182 assert_eq!(read(pub_verify.join("hello.txt")), "hello over https\n");
198 183
199- // Anonymous clone of a public repo must succeed.
200 let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git");184 let anon_url = format!("http://127.0.0.1:{http_port}/tahinli/pub.git");
201 let pub_anon = dir.join("pub-anon");185 let pub_anon = dir.join("pub-anon");
202 ok(186 ok(
@@ -214,7 +198,6 @@ async fn git_end_to_end() {
214 "anonymous shallow clone",198 "anonymous shallow clone",
215 );199 );
216 200
217- // SSH: push to the private repo with the registered key, then read it back.
218 let ssh_cmd = ssh_command(&key, ssh_port);201 let ssh_cmd = ssh_command(&key, ssh_port);
219 let ssh_env = [("GIT_SSH_COMMAND", ssh_cmd.as_str())];202 let ssh_env = [("GIT_SSH_COMMAND", ssh_cmd.as_str())];
220 let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git");203 let priv_ssh_url = format!("ssh://git@127.0.0.1:{ssh_port}/tahinli/priv.git");
@@ -243,7 +226,6 @@ async fn git_end_to_end() {
243 );226 );
244 assert_eq!(read(priv_verify.join("secret.txt")), "over ssh\n");227 assert_eq!(read(priv_verify.join("secret.txt")), "over ssh\n");
245 228
246- // Negative: private repo without credentials.
247 let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git");229 let priv_https_anon = format!("http://127.0.0.1:{http_port}/tahinli/priv.git");
248 rejected(230 rejected(
249 &git(&dir, &["clone", &priv_https_anon, "anon-priv"], &[]),231 &git(&dir, &["clone", &priv_https_anon, "anon-priv"], &[]),
@@ -257,7 +239,6 @@ async fn git_end_to_end() {
257 "401 must carry WWW-Authenticate"239 "401 must carry WWW-Authenticate"
258 );240 );
259 241
260- // Negative: bob is signed in but has no access, so the private repo looks absent.
261 let bob = login(&http, "bob", BOB_PW).await;242 let bob = login(&http, "bob", BOB_PW).await;
262 let bob_page = http.get_cookie("/tahinli/priv", &bob).await;243 let bob_page = http.get_cookie("/tahinli/priv", &bob).await;
263 assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv");244 assert_eq!(bob_page.status, 404, "bob's web view of tahinli/priv");
@@ -265,7 +246,6 @@ async fn git_end_to_end() {
265 let bob_refs = http.get_basic(refs_path, "bob", &bob_token).await;246 let bob_refs = http.get_basic(refs_path, "bob", &bob_token).await;
266 assert_eq!(bob_refs.status, 404, "bob's info/refs on tahinli/priv");247 assert_eq!(bob_refs.status, 404, "bob's info/refs on tahinli/priv");
267 248
268- // Negative: a wrong token is rejected.
269 let wrong = http249 let wrong = http
270 .get_basic(refs_path, "tahinli", "forge_notarealtoken")250 .get_basic(refs_path, "tahinli", "forge_notarealtoken")
271 .await;251 .await;
@@ -277,7 +257,6 @@ async fn git_end_to_end() {
277 "clone with wrong token",257 "clone with wrong token",
278 );258 );
279 259
280- // Negative: deleting the default branch is rejected by pre-receive.
281 let delete = git(&pub_verify, &["push", "origin", "--delete", "main"], &[]);260 let delete = git(&pub_verify, &["push", "origin", "--delete", "main"], &[]);
282 let text = rejected(&delete, "deleting main");261 let text = rejected(&delete, "deleting main");
283 assert!(262 assert!(
@@ -285,7 +264,6 @@ async fn git_end_to_end() {
285 "delete message: {text}"264 "delete message: {text}"
286 );265 );
287 266
288- // Negative: a force-push to main after amending the commit is rejected.
289 set_identity(&pub_verify);267 set_identity(&pub_verify);
290 ok(268 ok(
291 &git(269 &git(
@@ -310,7 +288,6 @@ async fn git_end_to_end() {
310 "force-push message: {text}"288 "force-push message: {text}"
311 );289 );
312 290
313- // main must still point at the commit that was pushed.
314 let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"], &[]);291 let ls = git(&dir, &["ls-remote", &pub_url, "refs/heads/main"], &[]);
315 ok(&ls, "ls-remote main");292 ok(&ls, "ls-remote main");
316 let remote_main = String::from_utf8_lossy(&ls.stdout);293 let remote_main = String::from_utf8_lossy(&ls.stdout);
@@ -319,7 +296,6 @@ async fn git_end_to_end() {
319 "main moved after rejected pushes: {remote_main}"296 "main moved after rejected pushes: {remote_main}"
320 );297 );
321 298
322- // A force push to another branch takes the old commit's page down and marks it for removal.
323 ok(299 ok(
324 &git(300 &git(
325 &pub_verify,301 &pub_verify,
@@ -365,7 +341,6 @@ async fn git_end_to_end() {
365 "the force push marks the repo for pruning"341 "the force push marks the repo for pruning"
366 );342 );
367 343
368- // Negative: an SSH key that is not registered is refused.
369 let rogue = dir.join("rogue");344 let rogue = dir.join("rogue");
370 gen_key(&rogue);345 gen_key(&rogue);
371 let rogue_cmd = ssh_command(&rogue, ssh_port);346 let rogue_cmd = ssh_command(&rogue, ssh_port);
@@ -379,7 +354,6 @@ async fn git_end_to_end() {
379 "rogue key message: {text}"354 "rogue key message: {text}"
380 );355 );
381 356
382- // Negative: an injected path in an SSH exec request is refused by the strict parser.
383 let injected = Command::new("ssh")357 let injected = Command::new("ssh")
384 .args(ssh_opts(&key, ssh_port))358 .args(ssh_opts(&key, ssh_port))
385 .arg("git@127.0.0.1")359 .arg("git@127.0.0.1")
@@ -388,7 +362,6 @@ async fn git_end_to_end() {
388 .expect("run ssh");362 .expect("run ssh");
389 rejected(&injected, "ssh exec with injected path");363 rejected(&injected, "ssh exec with injected path");
390 364
391- // Negative: POST /new without a csrf field is forbidden.
392 let no_csrf = http365 let no_csrf = http
393 .post_form(366 .post_form(
394 "/new",367 "/new",
@@ -402,7 +375,6 @@ async fn git_end_to_end() {
402 .await;375 .await;
403 assert_eq!(no_csrf.status, 403, "POST /new without csrf");376 assert_eq!(no_csrf.status, 403, "POST /new without csrf");
404 377
405- // Negative: the dumb protocol (info/refs without ?service=) is forbidden.
406 let dumb = http.get("/tahinli/pub.git/info/refs", None).await;378 let dumb = http.get("/tahinli/pub.git/info/refs", None).await;
407 assert_eq!(dumb.status, 403, "info/refs without service");379 assert_eq!(dumb.status, 403, "info/refs without service");
408 assert!(380 assert!(
@@ -412,8 +384,6 @@ async fn git_end_to_end() {
412 );384 );
413 }385 }
414 386
415-/// A suspended user's personal access token is refused over HTTP git: pushes and clones that
416-/// worked a moment earlier fail once an admin suspends the account.
417 #[tokio::test]387 #[tokio::test]
418 async fn suspended_user_token_is_refused_over_http_git() {388 async fn suspended_user_token_is_refused_over_http_git() {
419 if !tool_on_path("git") {389 if !tool_on_path("git") {
@@ -432,7 +402,6 @@ async fn suspended_user_token_is_refused_over_http_git() {
432 let (_server, ports) = launch(&dir, ports).await;402 let (_server, ports) = launch(&dir, ports).await;
433 let http = Http::new(ports.http);403 let http = Http::new(ports.http);
434 404
435- // Bob makes a token and a private repo (a public one would still clone anonymously) of his own, and can push to it.
436 let bob = login(&http, "bob", BOB_PW).await;405 let bob = login(&http, "bob", BOB_PW).await;
437 let bob_token = create_token(&http, &bob, "suspend-token").await;406 let bob_token = create_token(&http, &bob, "suspend-token").await;
438 let page = http.get_cookie("/new", &bob).await;407 let page = http.get_cookie("/new", &bob).await;
@@ -466,7 +435,6 @@ async fn suspended_user_token_is_refused_over_http_git() {
466 "push before suspension",435 "push before suspension",
467 );436 );
468 437
469- // An admin suspends bob from his account page.
470 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;438 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
471 let list = http.get_cookie("/admin/users", &tahinli).await;439 let list = http.get_cookie("/admin/users", &tahinli).await;
472 assert_eq!(list.status, 200, "GET /admin/users");440 assert_eq!(list.status, 200, "GET /admin/users");
@@ -495,7 +463,6 @@ async fn suspended_user_token_is_refused_over_http_git() {
495 .await;463 .await;
496 assert_eq!(res.status, 303, "suspend bob: {}", res.body);464 assert_eq!(res.status, 303, "suspend bob: {}", res.body);
497 465
498- // The same token no longer works for a push or a clone.
499 commit_file(&work, "b.txt", "two\n", "second");466 commit_file(&work, "b.txt", "two\n", "second");
500 rejected(467 rejected(
501 &git(&work, &["push", "origin", "HEAD:main"], &[]),468 &git(&work, &["push", "origin", "HEAD:main"], &[]),
crates/forge-e2e/tests/e2e/i18n_e2e.rsmodified+0 -9
@@ -1,6 +1,3 @@
1-//! End-to-end checks for the interface language. Anonymous pages follow `Accept-Language`; a
2-//! signed-in user's stored language beats the browser; `<html lang>` matches the language used.
3-
4 use std::path::Path;1 use std::path::Path;
5 use std::process::Command;2 use std::process::Command;
6 3
@@ -11,7 +8,6 @@ use forge_core::Store;
11 8
12 const PW: &str = "tahinli-password-123";9 const PW: &str = "tahinli-password-123";
13 10
14-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
15 fn admin(config: &Path, args: &[&str]) {11 fn admin(config: &Path, args: &[&str]) {
16 let out = Command::new(bin())12 let out = Command::new(bin())
17 .arg("--config")13 .arg("--config")
@@ -28,14 +24,12 @@ fn admin(config: &Path, args: &[&str]) {
28 );24 );
29 }25 }
30 26
31-/// A running server plus the temp dir it lives in. The dir lasts as long as the test.
32 struct Env {27 struct Env {
33 _root: tempfile::TempDir,28 _root: tempfile::TempDir,
34 _server: Server,29 _server: Server,
35 http: Http,30 http: Http,
36 }31 }
37 32
38-/// Creates tahinli, then runs `seed` against the store before the server starts.
39 async fn start<F, Fut>(seed: F) -> Env33 async fn start<F, Fut>(seed: F) -> Env
40 where34 where
41 F: FnOnce(Store) -> Fut,35 F: FnOnce(Store) -> Fut,
@@ -92,7 +86,6 @@ async fn anonymous_pages_follow_the_browser_language() {
92 );86 );
93 assert!(english.body.contains("Username"), "English label");87 assert!(english.body.contains("Username"), "English label");
94 88
95- // No header, and a language this build does not have: English.
96 let plain = env.http.get_language("/login", None, None).await;89 let plain = env.http.get_language("/login", None, None).await;
97 assert!(plain.body.contains("<html lang=\"en\""));90 assert!(plain.body.contains("<html lang=\"en\""));
98 let german = env.http.get_language("/login", None, Some("de-DE")).await;91 let german = env.http.get_language("/login", None, Some("de-DE")).await;
@@ -115,7 +108,6 @@ async fn stored_language_beats_the_browser_for_a_signed_in_user() {
115 .await;108 .await;
116 let cookie = login(&env.http, "tahinli", PW).await;109 let cookie = login(&env.http, "tahinli", PW).await;
117 110
118- // The browser asks for English, but tahinli's stored preference is Turkish.
119 let page = env111 let page = env
120 .http112 .http
121 .get_language("/settings/security", Some(&cookie), Some("en-US,en;q=0.9"))113 .get_language("/settings/security", Some(&cookie), Some("en-US,en;q=0.9"))
@@ -161,7 +153,6 @@ async fn releases_page_follows_the_stored_turkish_language() {
161 .await;153 .await;
162 assert_eq!(created.status, 303, "create repo: {}", created.body);154 assert_eq!(created.status, 303, "create repo: {}", created.body);
163 155
164- // The browser asks for English, but tahinli's stored preference is Turkish.
165 let releases = env156 let releases = env
166 .http157 .http
167 .get_language("/tahinli/r/releases", Some(&cookie), Some("en-US,en;q=0.9"))158 .get_language("/tahinli/r/releases", Some(&cookie), Some("en-US,en;q=0.9"))
crates/forge-e2e/tests/e2e/issue_close_e2e.rsmodified+0 -23
@@ -1,8 +1,3 @@
1-//! End-to-end: pushes over HTTPS close and reference issues from commit messages.
2-//!
3-//! The server runs as a subprocess. Issues are created through the store on the same database
4-//! file, and every push is a real `git push` through the git HTTP endpoints.
5-
6 use crate::common::{1 use crate::common::{
7 Http, input_value, launch, login, pick_ports, relaunch, run_admin, tool_on_path, write_config,2 Http, input_value, launch, login, pick_ports, relaunch, run_admin, tool_on_path, write_config,
8 };3 };
@@ -17,7 +12,6 @@ use forge_core::Store;
17 const TAHINLI_PW: &str = "tahinli-password-123";12 const TAHINLI_PW: &str = "tahinli-password-123";
18 const BOB_PW: &str = "bob-password-4567";13 const BOB_PW: &str = "bob-password-4567";
19 14
20-/// Runs git with credential helpers disabled and returns stdout, trimmed. Panics on failure.
21 fn git(cwd: &Path, args: &[&str]) -> String {15 fn git(cwd: &Path, args: &[&str]) -> String {
22 let out = git_output(cwd, args, &[]);16 let out = git_output(cwd, args, &[]);
23 assert!(17 assert!(
@@ -40,7 +34,6 @@ fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
40 cmd.output().expect("run git")34 cmd.output().expect("run git")
41 }35 }
42 36
43-/// Writes `name`, commits it as tahinli, and returns the new HEAD.
44 fn commit_file(repo: &Path, name: &str, message: &str) -> String {37 fn commit_file(repo: &Path, name: &str, message: &str) -> String {
45 fs::write(repo.join(name), message).expect("write file");38 fs::write(repo.join(name), message).expect("write file");
46 git(repo, &["add", name]);39 git(repo, &["add", name]);
@@ -62,7 +55,6 @@ fn commit_file(repo: &Path, name: &str, message: &str) -> String {
62 git(repo, &["rev-parse", "HEAD"])55 git(repo, &["rev-parse", "HEAD"])
63 }56 }
64 57
65-/// Creates an access token through `/settings/tokens` and returns the token shown once.
66 async fn create_token(http: &Http, session: &str, name: &str) -> String {58 async fn create_token(http: &Http, session: &str, name: &str) -> String {
67 let page = http.get_cookie("/settings/keys", session).await;59 let page = http.get_cookie("/settings/keys", session).await;
68 assert_eq!(page.status, 200, "GET /settings/keys");60 assert_eq!(page.status, 200, "GET /settings/keys");
@@ -88,7 +80,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String {
88 token80 token
89 }81 }
90 82
91-/// Creates a public repo through `/new`.
92 async fn create_repo(http: &Http, session: &str, name: &str) {83 async fn create_repo(http: &Http, session: &str, name: &str) {
93 let page = http.get_cookie("/new", session).await;84 let page = http.get_cookie("/new", session).await;
94 assert_eq!(page.status, 200, "GET /new");85 assert_eq!(page.status, 200, "GET /new");
@@ -113,7 +104,6 @@ async fn create_repo(http: &Http, session: &str, name: &str) {
113 );104 );
114 }105 }
115 106
116-/// Polls `check` every 100ms until it returns true, failing after 5 seconds.
117 async fn eventually<F, Fut>(what: &str, mut check: F)107 async fn eventually<F, Fut>(what: &str, mut check: F)
118 where108 where
119 F: FnMut() -> Fut,109 F: FnMut() -> Fut,
@@ -129,7 +119,6 @@ where
129 }119 }
130 }120 }
131 121
132-/// The issue page for `number`, read as `session`.
133 async fn issue_page(http: &Http, session: &str, number: u32) -> String {122 async fn issue_page(http: &Http, session: &str, number: u32) -> String {
134 let res = http123 let res = http
135 .get_cookie(&format!("/tahinli/pub/issues/{number}"), session)124 .get_cookie(&format!("/tahinli/pub/issues/{number}"), session)
@@ -138,7 +127,6 @@ async fn issue_page(http: &Http, session: &str, number: u32) -> String {
138 res.body127 res.body
139 }128 }
140 129
141-/// Text of the state badge on an issue page, e.g. `Open` or `Closed`.
142 fn state_badge(body: &str) -> String {130 fn state_badge(body: &str) -> String {
143 let doc = scraper::Html::parse_document(body);131 let doc = scraper::Html::parse_document(body);
144 let selector = scraper::Selector::parse(".issue-badge").expect("selector");132 let selector = scraper::Selector::parse(".issue-badge").expect("selector");
@@ -155,7 +143,6 @@ async fn pushes_close_and_reference_issues() {
155 return;143 return;
156 }144 }
157 145
158- // Keep the path short: the internal unix socket path is limited to 108 bytes.
159 let root = tempfile::Builder::new()146 let root = tempfile::Builder::new()
160 .prefix("ice2e")147 .prefix("ice2e")
161 .tempdir_in("/tmp")148 .tempdir_in("/tmp")
@@ -168,7 +155,6 @@ async fn pushes_close_and_reference_issues() {
168 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);155 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
169 run_admin(&config, "bob", &[], BOB_PW);156 run_admin(&config, "bob", &[], BOB_PW);
170 157
171- // Web setup: log in, make a token and create the repo.
172 let (mut server, ports) = launch(&dir, ports).await;158 let (mut server, ports) = launch(&dir, ports).await;
173 let http_port = ports.http;159 let http_port = ports.http;
174 let http = Http::new(http_port);160 let http = Http::new(http_port);
@@ -176,8 +162,6 @@ async fn pushes_close_and_reference_issues() {
176 let token = create_token(&http, &tahinli, "issue-close-token").await;162 let token = create_token(&http, &tahinli, "issue-close-token").await;
177 create_repo(&http, &tahinli, "pub").await;163 create_repo(&http, &tahinli, "pub").await;
178 164
179- // The database file is locked while the server runs, so stop it, create the issues through
180- // the store, and start the server again on the same ports.
181 drop(server);165 drop(server);
182 {166 {
183 let store = Store::open(&dir.join("forge.db"))167 let store = Store::open(&dir.join("forge.db"))
@@ -203,7 +187,6 @@ async fn pushes_close_and_reference_issues() {
203 server = relaunch(&config, &log_path, ports).await;187 server = relaunch(&config, &log_path, ports).await;
204 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;188 let tahinli = login(&http, "tahinli", TAHINLI_PW).await;
205 189
206- // Push over HTTPS with the token.
207 let url = format!("http://tahinli:{token}@127.0.0.1:{http_port}/tahinli/pub.git");190 let url = format!("http://tahinli:{token}@127.0.0.1:{http_port}/tahinli/pub.git");
208 let work = dir.join("work");191 let work = dir.join("work");
209 git(192 git(
@@ -213,16 +196,12 @@ async fn pushes_close_and_reference_issues() {
213 let base = commit_file(&work, "base.txt", "base commit");196 let base = commit_file(&work, "base.txt", "base commit");
214 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);197 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
215 198
216- // A commit that references #3 on a non-default branch must not close it.
217 git(&work, &["checkout", "-q", "-b", "topic"]);199 git(&work, &["checkout", "-q", "-b", "topic"]);
218 let topic_oid = commit_file(&work, "topic.txt", "fixes #3 on a topic branch");200 let topic_oid = commit_file(&work, "topic.txt", "fixes #3 on a topic branch");
219 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/topic"]);201 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/topic"]);
220 202
221- // Default branch: one closing reference and one plain reference.
222 git(&work, &["checkout", "-q", "-B", "mainline", &base]);203 git(&work, &["checkout", "-q", "-B", "mainline", &base]);
223 let main_oid = commit_file(&work, "main.txt", "Fixes #1, refs #2");204 let main_oid = commit_file(&work, "main.txt", "Fixes #1, refs #2");
224- // The same commit goes to another branch first. That push is not processed, so the
225- // push to main below must produce exactly one referenced event.
226 git(205 git(
227 &work,206 &work,
228 &["push", "-q", "origin", "HEAD:refs/heads/dup-of-main"],207 &["push", "-q", "origin", "HEAD:refs/heads/dup-of-main"],
@@ -250,8 +229,6 @@ async fn pushes_close_and_reference_issues() {
250 let page2 = issue_page(&http, &tahinli, 2).await;229 let page2 = issue_page(&http, &tahinli, 2).await;
251 assert_eq!(state_badge(&page2), "Open", "#2 is only referenced");230 assert_eq!(state_badge(&page2), "Open", "#2 is only referenced");
252 231
253- // Nothing observable marks the end of a background run for a non-matching push, so give the
254- // topic and dup-branch work time to finish before checking the counts again.
255 tokio::time::sleep(Duration::from_secs(2)).await;232 tokio::time::sleep(Duration::from_secs(2)).await;
256 let page2 = issue_page(&http, &tahinli, 2).await;233 let page2 = issue_page(&http, &tahinli, 2).await;
257 assert_eq!(234 assert_eq!(
crates/forge-e2e/tests/e2e/lfs_e2e.rsmodified+0 -16
@@ -1,10 +1,3 @@
1-//! End-to-end test for Git LFS. It starts the real `forge` binary and drives it with the real
2-//! `git` and `git lfs` clients over smart HTTP, authenticated with a personal access token.
3-//!
4-//! The test needs `git lfs` on PATH. Without it, the test prints a message and returns early.
5-//! Git config is isolated from the developer's machine: `HOME` and `GIT_CONFIG_GLOBAL` point into
6-//! the test's temp dir.
7-
8 use crate::common::{1 use crate::common::{
9 Http, describe, input_value, launch, login, pick_ports, run_admin, write_config,2 Http, describe, input_value, launch, login, pick_ports, run_admin, write_config,
10 };3 };
@@ -19,7 +12,6 @@ fn ok(out: &Output, what: &str) {
19 assert!(out.status.success(), "{what} failed:\n{}", describe(out));12 assert!(out.status.success(), "{what} failed:\n{}", describe(out));
20 }13 }
21 14
22-/// Runs git in `cwd` with `env` applied on top of the inherited environment.
23 fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {15 fn git(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
24 let mut cmd = Command::new("git");16 let mut cmd = Command::new("git");
25 cmd.current_dir(cwd)17 cmd.current_dir(cwd)
@@ -43,14 +35,12 @@ fn git_lfs_installed() -> bool {
43 .is_ok_and(|out| out.status.success())35 .is_ok_and(|out| out.status.success())
44 }36 }
45 37
46-/// Deterministic bytes that are not all one value, so a wrong or empty download fails the check.
47 fn payload() -> Vec<u8> {38 fn payload() -> Vec<u8> {
48 (0..FILE_SIZE)39 (0..FILE_SIZE)
49 .map(|i| (i.wrapping_mul(31) % 251) as u8)40 .map(|i| (i.wrapping_mul(31) % 251) as u8)
50 .collect()41 .collect()
51 }42 }
52 43
53-/// Creates an access token through `/settings/tokens` and returns the token shown once.
54 async fn create_token(http: &Http, session: &str, name: &str) -> String {44 async fn create_token(http: &Http, session: &str, name: &str) -> String {
55 let page = http.get("/settings/keys", Some(session)).await;45 let page = http.get("/settings/keys", Some(session)).await;
56 assert_eq!(page.status, 200, "GET /settings/keys");46 assert_eq!(page.status, 200, "GET /settings/keys");
@@ -76,7 +66,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String {
76 token66 token
77 }67 }
78 68
79-/// Creates a repo through `/new`.
80 async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {69 async fn create_repo(http: &Http, session: &str, name: &str, visibility: &str) {
81 let page = http.get("/new", Some(session)).await;70 let page = http.get("/new", Some(session)).await;
82 assert_eq!(page.status, 200, "GET /new");71 assert_eq!(page.status, 200, "GET /new");
@@ -108,7 +97,6 @@ async fn lfs_end_to_end() {
108 return;97 return;
109 }98 }
110 99
111- // Keep the path short: the internal unix socket path is limited to 108 bytes.
112 let root = tempfile::Builder::new()100 let root = tempfile::Builder::new()
113 .prefix("flfs")101 .prefix("flfs")
114 .tempdir_in("/tmp")102 .tempdir_in("/tmp")
@@ -125,7 +113,6 @@ async fn lfs_end_to_end() {
125 let token = create_token(&http, &session, "lfs-e2e").await;113 let token = create_token(&http, &session, "lfs-e2e").await;
126 create_repo(&http, &session, "lfs", "public").await;114 create_repo(&http, &session, "lfs", "public").await;
127 115
128- // Isolated git config for every client call below.
129 let global = dir.join("gitconfig");116 let global = dir.join("gitconfig");
130 let iso = [117 let iso = [
131 ("HOME", path_str(&dir)),118 ("HOME", path_str(&dir)),
@@ -136,7 +123,6 @@ async fn lfs_end_to_end() {
136 ports.http123 ports.http
137 );124 );
138 125
139- // Push a 100 KiB file tracked by LFS.
140 let work = dir.join("work");126 let work = dir.join("work");
141 ok(127 ok(
142 &git(&dir, &["clone", &url, path_str(&work)], &iso),128 &git(&dir, &["clone", &url, path_str(&work)], &iso),
@@ -188,7 +174,6 @@ async fn lfs_end_to_end() {
188 "git push",174 "git push",
189 );175 );
190 176
191- // Clone again with smudge on and check that the bytes come back intact.
192 let verify = dir.join("verify");177 let verify = dir.join("verify");
193 let smudge = [iso[0], iso[1], ("GIT_LFS_SKIP_SMUDGE", "0")];178 let smudge = [iso[0], iso[1], ("GIT_LFS_SKIP_SMUDGE", "0")];
194 ok(179 ok(
@@ -208,7 +193,6 @@ async fn lfs_end_to_end() {
208 content.len()193 content.len()
209 );194 );
210 195
211- // The blob page shows the object as stored in LFS.
212 let page = http196 let page = http
213 .get("/tahinli/lfs/blob/main/data.bin", Some(&session))197 .get("/tahinli/lfs/blob/main/data.bin", Some(&session))
214 .await;198 .await;
crates/forge-e2e/tests/e2e/main.rsmodified+0 -4
@@ -1,7 +1,3 @@
1-//! One integration test binary for forge-web. Every file in this directory is a module of this
2-//! crate, so the package links one test executable instead of one per file. The shared support
3-//! lives in `common`.
4-
5 mod common;1 mod common;
6 2
7 mod account_mail_e2e;3 mod account_mail_e2e;
crates/forge-e2e/tests/e2e/mirrors_e2e.rsmodified+0 -41
@@ -1,14 +1,3 @@
1-//! End-to-end: pull and push mirrors against one real `forge` binary, talking to itself over
2-//! HTTP smart git. The instance allows plain HTTP and allow-lists `127.0.0.1` in `[webhooks]`, so
3-//! its own mirror worker may reach the loopback listener. Nothing else about the SSRF guard is
4-//! relaxed.
5-//!
6-//! Scenarios:
7-//! - pull mirror `dst` of `tahinli/src` (heads and tags) created through the new-repo form, then a
8-//! second change picked up by "Sync now"; a push to `dst` is refused;
9-//! - push mirror `pm` to `tahinli/target` (created empty) after a push to `pm`;
10-//! - the mirror pages and the server log never contain the access token.
11-
12 use crate::common::{1 use crate::common::{
13 Http, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path,2 Http, Server, input_value, launch_with, login, pick_ports, run_admin, tool_on_path,
14 write_config_with,3 write_config_with,
@@ -22,11 +11,8 @@ use std::time::{Duration, Instant};
22 const TAHINLI_PW: &str = "tahinli-password-123";11 const TAHINLI_PW: &str = "tahinli-password-123";
23 const WEBHOOK_TOML: &str = "\n[webhooks]\nallow_http = true\nallowed_hosts = [\"127.0.0.1\"]\n\n[mirrors]\npush_debounce_secs = 0\n";12 const WEBHOOK_TOML: &str = "\n[webhooks]\nallow_http = true\nallowed_hosts = [\"127.0.0.1\"]\n\n[mirrors]\npush_debounce_secs = 0\n";
24 const SYNC_TIMEOUT: Duration = Duration::from_secs(30);13 const SYNC_TIMEOUT: Duration = Duration::from_secs(30);
25-/// Push mirrors run after the push debounce, which this test sets to 0 (production: 10s). The
26-/// worker wakes on the push itself, so this only needs room for the git sync.
27 const PUSH_TIMEOUT: Duration = Duration::from_secs(90);14 const PUSH_TIMEOUT: Duration = Duration::from_secs(90);
28 15
29-/// The `action` of every form whose action ends with `suffix`, in page order.
30 fn form_actions(body: &str, suffix: &str) -> Vec<String> {16 fn form_actions(body: &str, suffix: &str) -> Vec<String> {
31 let doc = scraper::Html::parse_document(body);17 let doc = scraper::Html::parse_document(body);
32 let selector = scraper::Selector::parse("form[action]").expect("selector");18 let selector = scraper::Selector::parse("form[action]").expect("selector");
@@ -37,8 +23,6 @@ fn form_actions(body: &str, suffix: &str) -> Vec<String> {
37 .collect()23 .collect()
38 }24 }
39 25
40-/// Fixed identity and config isolation for every git this file spawns, so the result does not
41-/// depend on the machine's global git config (a clean CI container has none).
42 const GIT_HERMETIC_ENV: &[(&str, &str)] = &[26 const GIT_HERMETIC_ENV: &[(&str, &str)] = &[
43 ("GIT_AUTHOR_NAME", "tahinli"),27 ("GIT_AUTHOR_NAME", "tahinli"),
44 ("GIT_AUTHOR_EMAIL", "tahinli@example.com"),28 ("GIT_AUTHOR_EMAIL", "tahinli@example.com"),
@@ -48,7 +32,6 @@ const GIT_HERMETIC_ENV: &[(&str, &str)] = &[
48 ("GIT_CONFIG_NOSYSTEM", "1"),32 ("GIT_CONFIG_NOSYSTEM", "1"),
49 ];33 ];
50 34
51-/// Runs git with credential helpers disabled and extra env. Returns the raw output.
52 fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {35 fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
53 let mut cmd = Command::new("git");36 let mut cmd = Command::new("git");
54 cmd.current_dir(cwd)37 cmd.current_dir(cwd)
@@ -61,7 +44,6 @@ fn git_output(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {
61 cmd.output().expect("run git")44 cmd.output().expect("run git")
62 }45 }
63 46
64-/// Runs git, returning stdout trimmed. Panics on failure.
65 fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {47 fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {
66 let out = git_output(cwd, args, env);48 let out = git_output(cwd, args, env);
67 assert!(49 assert!(
@@ -76,7 +58,6 @@ fn git(cwd: &Path, args: &[&str]) -> String {
76 git_env(cwd, args, &[])58 git_env(cwd, args, &[])
77 }59 }
78 60
79-/// Writes `file`, commits it as `who` and returns the new HEAD.
80 fn commit(repo: &Path, file: &str, contents: &str, message: &str) -> String {61 fn commit(repo: &Path, file: &str, contents: &str, message: &str) -> String {
81 fs::write(repo.join(file), contents).expect("write file");62 fs::write(repo.join(file), contents).expect("write file");
82 git(repo, &["add", file]);63 git(repo, &["add", file]);
@@ -93,7 +74,6 @@ fn commit(repo: &Path, file: &str, contents: &str, message: &str) -> String {
93 git(repo, &["rev-parse", "HEAD"])74 git(repo, &["rev-parse", "HEAD"])
94 }75 }
95 76
96-/// Clones `url` into `into` (a path that does not exist yet) and returns it.
97 fn clone(url: &str, into: &Path) -> PathBuf {77 fn clone(url: &str, into: &Path) -> PathBuf {
98 let parent = into.parent().expect("clone target has a parent");78 let parent = into.parent().expect("clone target has a parent");
99 git(79 git(
@@ -103,13 +83,10 @@ fn clone(url: &str, into: &Path) -> PathBuf {
103 into.to_path_buf()83 into.to_path_buf()
104 }84 }
105 85
106-/// The HTTPS remote for `owner/repo`, authenticated with a token.
107 fn remote(port: u16, token: &str, owner: &str, repo: &str) -> String {86 fn remote(port: u16, token: &str, owner: &str, repo: &str) -> String {
108 format!("http://tahinli:{token}@127.0.0.1:{port}/{owner}/{repo}.git")87 format!("http://tahinli:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
109 }88 }
110 89
111-/// The heads and tags a remote advertises, as sorted `sha refname` lines. HEAD is left out.
112-/// Returns `None` if the remote cannot be listed.
113 fn branches_and_tags(url: &str) -> Option<BTreeSet<String>> {90 fn branches_and_tags(url: &str) -> Option<BTreeSet<String>> {
114 let out = git_output(&std::env::temp_dir(), &["ls-remote", url], &[]);91 let out = git_output(&std::env::temp_dir(), &["ls-remote", url], &[]);
115 if !out.status.success() {92 if !out.status.success() {
@@ -124,7 +101,6 @@ fn branches_and_tags(url: &str) -> Option<BTreeSet<String>> {
124 )101 )
125 }102 }
126 103
127-/// The sha a remote branch points at, if the branch exists.
128 fn remote_head(url: &str, branch: &str) -> Option<String> {104 fn remote_head(url: &str, branch: &str) -> Option<String> {
129 let out = git_output(105 let out = git_output(
130 &std::env::temp_dir(),106 &std::env::temp_dir(),
@@ -140,7 +116,6 @@ fn remote_head(url: &str, branch: &str) -> Option<String> {
140 .map(str::to_owned)116 .map(str::to_owned)
141 }117 }
142 118
143-/// Polls `check` every 200ms until it returns true, failing after `SYNC_TIMEOUT`.
144 async fn wait_for(what: &str, check: impl Fn() -> bool) {119 async fn wait_for(what: &str, check: impl Fn() -> bool) {
145 let deadline = Instant::now() + SYNC_TIMEOUT;120 let deadline = Instant::now() + SYNC_TIMEOUT;
146 while !check() {121 while !check() {
@@ -152,14 +127,12 @@ async fn wait_for(what: &str, check: impl Fn() -> bool) {
152 }127 }
153 }128 }
154 129
155-/// The session's CSRF token, scraped from the token settings page.
156 async fn csrf_token(http: &Http, session: &str) -> String {130 async fn csrf_token(http: &Http, session: &str) -> String {
157 let page = http.get_cookie("/settings/keys", session).await;131 let page = http.get_cookie("/settings/keys", session).await;
158 assert_eq!(page.status, 200, "GET /settings/keys");132 assert_eq!(page.status, 200, "GET /settings/keys");
159 input_value(&page.body, "csrf")133 input_value(&page.body, "csrf")
160 }134 }
161 135
162-/// Creates an access token through `/settings/tokens` and returns the token shown once.
163 async fn create_token(http: &Http, session: &str, name: &str) -> String {136 async fn create_token(http: &Http, session: &str, name: &str) -> String {
164 let csrf = csrf_token(http, session).await;137 let csrf = csrf_token(http, session).await;
165 let res = http138 let res = http
@@ -183,7 +156,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String {
183 token156 token
184 }157 }
185 158
186-/// Submits the new-repo form. `mirror` adds the "Mirror an existing repository" fields.
187 async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, &str, &str)>) {159 async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str, &str, &str)>) {
188 let page = http.get_cookie("/new", session).await;160 let page = http.get_cookie("/new", session).await;
189 assert_eq!(page.status, 200, "GET /new");161 assert_eq!(page.status, 200, "GET /new");
@@ -211,7 +183,6 @@ async fn new_repo(http: &Http, session: &str, name: &str, mirror: Option<(&str,
211 );183 );
212 }184 }
213 185
214-/// Adds a push mirror to `tahinli/repo` through its settings page.
215 async fn add_push_mirror(http: &Http, session: &str, repo: &str, url: &str, secret: &str) {186 async fn add_push_mirror(http: &Http, session: &str, repo: &str, url: &str, secret: &str) {
216 let path = format!("/tahinli/{repo}/settings/mirrors");187 let path = format!("/tahinli/{repo}/settings/mirrors");
217 let page = http.get_cookie(&path, session).await;188 let page = http.get_cookie(&path, session).await;
@@ -233,7 +204,6 @@ async fn add_push_mirror(http: &Http, session: &str, repo: &str, url: &str, secr
233 assert_eq!(res.status, 303, "add push mirror: {}", res.body);204 assert_eq!(res.status, 303, "add push mirror: {}", res.body);
234 }205 }
235 206
236-/// Clicks "Sync now" on the first mirror of `tahinli/repo`.
237 async fn sync_now(http: &Http, session: &str, repo: &str) {207 async fn sync_now(http: &Http, session: &str, repo: &str) {
238 let path = format!("/tahinli/{repo}/settings/mirrors");208 let path = format!("/tahinli/{repo}/settings/mirrors");
239 let page = http.get_cookie(&path, session).await;209 let page = http.get_cookie(&path, session).await;
@@ -249,8 +219,6 @@ async fn sync_now(http: &Http, session: &str, repo: &str) {
249 assert_eq!(res.status, 303, "sync now: {}", res.body);219 assert_eq!(res.status, 303, "sync now: {}", res.body);
250 }220 }
251 221
252-/// A running server with its own temp data dir. Field order matters: the server is dropped (and
253-/// killed) before the temp dir is removed.
254 struct Booted {222 struct Booted {
255 _server: Server,223 _server: Server,
256 _root: tempfile::TempDir,224 _root: tempfile::TempDir,
@@ -259,12 +227,10 @@ struct Booted {
259 http_port: u16,227 http_port: u16,
260 }228 }
261 229
262-/// Creates tahinli (admin) and boots the server with plain HTTP and loopback mirrors allowed.
263 async fn boot() -> Booted {230 async fn boot() -> Booted {
264 if !tool_on_path("git") {231 if !tool_on_path("git") {
265 panic!("`git` was not found on PATH");232 panic!("`git` was not found on PATH");
266 }233 }
267- // Keep the path short: the internal unix socket path is limited to 108 bytes.
268 let root = tempfile::Builder::new()234 let root = tempfile::Builder::new()
269 .prefix("mr2e")235 .prefix("mr2e")
270 .tempdir_in("/tmp")236 .tempdir_in("/tmp")
@@ -284,7 +250,6 @@ async fn boot() -> Booted {
284 }250 }
285 }251 }
286 252
287-/// The server log, for assertion messages and the token leak check.
288 fn server_log(b: &Booted) -> String {253 fn server_log(b: &Booted) -> String {
289 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()254 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
290 }255 }
@@ -296,7 +261,6 @@ async fn pull_and_push_mirrors_sync_over_smart_http() {
296 let token = create_token(&b.http, &session, "mirror-token").await;261 let token = create_token(&b.http, &session, "mirror-token").await;
297 let port = b.http_port;262 let port = b.http_port;
298 263
299- // Source repo with a commit on main, a second branch and an annotated tag.
300 new_repo(&b.http, &session, "src", None).await;264 new_repo(&b.http, &session, "src", None).await;
301 let src_work = clone(265 let src_work = clone(
302 &remote(port, &token, "tahinli", "src"),266 &remote(port, &token, "tahinli", "src"),
@@ -315,7 +279,6 @@ async fn pull_and_push_mirrors_sync_over_smart_http() {
315 assert!(src_refs.iter().any(|l| l.ends_with("refs/tags/v1")));279 assert!(src_refs.iter().any(|l| l.ends_with("refs/tags/v1")));
316 assert!(src_refs.iter().any(|l| l.ends_with("refs/heads/feature")));280 assert!(src_refs.iter().any(|l| l.ends_with("refs/heads/feature")));
317 281
318- // Pull mirror created through the new-repo form. Creation schedules the first sync now.
319 new_repo(282 new_repo(
320 &b.http,283 &b.http,
321 &session,284 &session,
@@ -333,7 +296,6 @@ async fn pull_and_push_mirrors_sync_over_smart_http() {
333 Some(first.as_str())296 Some(first.as_str())
334 );297 );
335 298
336- // A push to the pull mirror is refused by pre-receive.
337 let dst_work = clone(&dst_url, &b.dir.join("dst-work"));299 let dst_work = clone(&dst_url, &b.dir.join("dst-work"));
338 commit(&dst_work, "local.txt", "local\n", "local change");300 commit(&dst_work, "local.txt", "local\n", "local change");
339 let refused = git_output(&dst_work, &["push", "origin", "HEAD:refs/heads/main"], &[]);301 let refused = git_output(&dst_work, &["push", "origin", "HEAD:refs/heads/main"], &[]);
@@ -347,7 +309,6 @@ async fn pull_and_push_mirrors_sync_over_smart_http() {
347 "rejection should name the pull mirror:\n{stderr}"309 "rejection should name the pull mirror:\n{stderr}"
348 );310 );
349 311
350- // A new commit on src, picked up by "Sync now" on dst.
351 let second = commit(&src_work, "next.txt", "next\n", "second commit");312 let second = commit(&src_work, "next.txt", "next\n", "second commit");
352 git(&src_work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);313 git(&src_work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
353 sync_now(&b.http, &session, "dst").await;314 sync_now(&b.http, &session, "dst").await;
@@ -356,7 +317,6 @@ async fn pull_and_push_mirrors_sync_over_smart_http() {
356 })317 })
357 .await;318 .await;
358 319
359- // Push mirror: an empty target repo receives pm's commit.
360 new_repo(&b.http, &session, "target", None).await;320 new_repo(&b.http, &session, "target", None).await;
361 new_repo(&b.http, &session, "pm", None).await;321 new_repo(&b.http, &session, "pm", None).await;
362 let target_url = format!("http://127.0.0.1:{port}/tahinli/target.git");322 let target_url = format!("http://127.0.0.1:{port}/tahinli/target.git");
@@ -403,7 +363,6 @@ async fn pull_and_push_mirrors_sync_over_smart_http() {
403 );363 );
404 }364 }
405 365
406- // The token never shows up in the mirror pages or the server log.
407 for repo in ["dst", "pm"] {366 for repo in ["dst", "pm"] {
408 let page = b367 let page = b
409 .http368 .http
crates/forge-e2e/tests/e2e/oci_e2e.rsmodified+0 -21
@@ -1,10 +1,3 @@
1-//! Black-box tests for the container registry. They start the real `forge` binary and drive the
2-//! OCI Distribution API over HTTP the way a container client does: the auth probe, the token
3-//! exchange, monolithic and chunked blob uploads, manifests by tag and digest, the tag list, mounts,
4-//! deletes and the garbage collection they trigger. Private images and the packages scope are set
5-//! up through the store before the server starts, since the web has no way to make one private.
6-//! The last test drives podman when it is installed; it is ignored by default.
7-
8 use crate::common::{Server, bin, describe, launch, pick_ports, tool_on_path, write_config};1 use crate::common::{Server, bin, describe, launch, pick_ports, tool_on_path, write_config};
9 use std::path::Path;2 use std::path::Path;
10 use std::process::Command;3 use std::process::Command;
@@ -40,7 +33,6 @@ impl Resp {
40 serde_json::from_slice(&self.body).expect("json body")33 serde_json::from_slice(&self.body).expect("json body")
41 }34 }
42 35
43- /// The `code` of the first OCI error, for asserting error codes.
44 fn error_code(&self) -> String {36 fn error_code(&self) -> String {
45 self.json()["errors"][0]["code"]37 self.json()["errors"][0]["code"]
46 .as_str()38 .as_str()
@@ -67,7 +59,6 @@ impl Http {
67 }59 }
68 }60 }
69 61
70- /// Sends one request. `auth` is the whole Authorization value, when there is one.
71 async fn send(62 async fn send(
72 &self,63 &self,
73 method: reqwest::Method,64 method: reqwest::Method,
@@ -116,7 +107,6 @@ impl Http {
116 }107 }
117 }108 }
118 109
119-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
120 fn admin(config: &Path, args: &[&str]) {110 fn admin(config: &Path, args: &[&str]) {
121 let out = Command::new(bin())111 let out = Command::new(bin())
122 .arg("--config")112 .arg("--config")
@@ -133,7 +123,6 @@ fn admin(config: &Path, args: &[&str]) {
133 );123 );
134 }124 }
135 125
136-/// A running server. The temp dir lives as long as the test.
137 struct Env {126 struct Env {
138 _root: tempfile::TempDir,127 _root: tempfile::TempDir,
139 _server: Server,128 _server: Server,
@@ -141,7 +130,6 @@ struct Env {
141 port: u16,130 port: u16,
142 }131 }
143 132
144-/// Creates the users `tahinli` and `bob`, runs `seed` on the store, then starts the server.
145 async fn start<F, Fut>(seed: F) -> Env133 async fn start<F, Fut>(seed: F) -> Env
146 where134 where
147 F: FnOnce(Store) -> Fut,135 F: FnOnce(Store) -> Fut,
@@ -169,7 +157,6 @@ where
169 }157 }
170 }158 }
171 159
172-/// Stores a token for `user` with the given scopes. `token` is the plaintext a client will send.
173 async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) {160 async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) {
174 let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect();161 let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect();
175 store162 store
@@ -205,7 +192,6 @@ fn blob_path(bytes: &[u8]) -> String {
205 format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes))192 format!("/v2/tahinli/app/blobs/{}", sha256_digest(bytes))
206 }193 }
207 194
208-/// The bearer header a client gets from the token endpoint with Basic `tahinli:<token>`.
209 async fn bearer_for(http: &Http, token: &str) -> String {195 async fn bearer_for(http: &Http, token: &str) -> String {
210 let res = http196 let res = http
211 .send(197 .send(
@@ -229,7 +215,6 @@ fn basic(user: &str, password: &str) -> String {
229 format!("Basic {encoded}")215 format!("Basic {encoded}")
230 }216 }
231 217
232-/// Pushes a blob in one request with its digest.
233 async fn push_blob(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp {218 async fn push_blob(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp {
234 let digest = sha256_digest(bytes);219 let digest = sha256_digest(bytes);
235 http.post(220 http.post(
@@ -240,7 +225,6 @@ async fn push_blob(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp {
240 .await225 .await
241 }226 }
242 227
243-/// Pushes a blob in three chunks, then closes the upload with its digest.
244 async fn push_blob_chunked(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp {228 async fn push_blob_chunked(http: &Http, repo: &str, auth: &str, bytes: &[u8]) -> Resp {
245 let start = http229 let start = http
246 .post(&format!("/v2/{repo}/blobs/uploads/"), Some(auth), None)230 .post(&format!("/v2/{repo}/blobs/uploads/"), Some(auth), None)
@@ -281,7 +265,6 @@ async fn push_blob_chunked(http: &Http, repo: &str, auth: &str, bytes: &[u8]) ->
281 .await265 .await
282 }266 }
283 267
284-/// An image manifest naming `config` and `layers`, as the JSON a client pushes.
285 fn manifest(config: &[u8], layers: &[&[u8]]) -> Vec<u8> {268 fn manifest(config: &[u8], layers: &[&[u8]]) -> Vec<u8> {
286 serde_json::to_vec(&serde_json::json!({269 serde_json::to_vec(&serde_json::json!({
287 "schemaVersion": 2,270 "schemaVersion": 2,
@@ -655,12 +638,10 @@ async fn writes_need_the_packages_scope_and_the_owner() {
655 assert_eq!(res.status, 202);638 assert_eq!(res.status, 202);
656 }639 }
657 640
658-/// A bearer header for `token` with no scope, read through the token endpoint as Basic.
659 async fn bearer_for_scope_less(http: &Http, token: &str) -> String {641 async fn bearer_for_scope_less(http: &Http, token: &str) -> String {
660 bearer_for(http, token).await642 bearer_for(http, token).await
661 }643 }
662 644
663-/// A bearer header for `token` owned by `who`, read through the token endpoint as Basic.
664 async fn bearer_for_as(http: &Http, who: &str, token: &str) -> String {645 async fn bearer_for_as(http: &Http, who: &str, token: &str) -> String {
665 let res = http646 let res = http
666 .send(647 .send(
@@ -761,8 +742,6 @@ async fn deleting_tags_and_manifests_keeps_fresh_blobs_for_the_grace_period() {
761 .status,742 .status,
762 404743 404
763 );744 );
764- // The blobs were pushed just now: the sweep keeps a link newer than the grace period, since a
765- // push can still be on its way to a manifest. The store test covers the sweep after it.
766 assert_eq!(745 assert_eq!(
767 http.get(&blob_path(&layer_b), Some(&auth)).await.status,746 http.get(&blob_path(&layer_b), Some(&auth)).await.status,
768 200747 200
crates/forge-e2e/tests/e2e/orgs_core_e2e.rsmodified+0 -13
@@ -1,8 +1,3 @@
1-//! Black-box tests for the organization rule that an org never authenticates: password login, a
2-//! session row naming an org, an API token, and HTTP Basic git access. Like the other e2e tests,
3-//! this starts the real `forge` binary and drives it over HTTP. The org rows and their credentials
4-//! are written straight into the database before the server starts.
5-
6 use crate::common::{1 use crate::common::{
7 Http, Resp, Server, bin, cookie_named, describe, input_value, launch, pick_ports, write_config,2 Http, Resp, Server, bin, cookie_named, describe, input_value, launch, pick_ports, write_config,
8 };3 };
@@ -14,16 +9,13 @@ use std::time::Duration;
14 use forge_core::token::hash_token;9 use forge_core::token::hash_token;
15 use forge_core::{Store, Visibility};10 use forge_core::{Store, Visibility};
16 11
17-/// Each test starts a server on ports picked just before, so the tests run one at a time.
18 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =12 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =
19 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));13 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
20 14
21 const PW: &str = "tahinli-password-123";15 const PW: &str = "tahinli-password-123";
22-/// A raw API token and a raw session token for the org. Hashed when stored.
23 const ORG_TOKEN: &str = "forge_org_token_for_tests_0123456789";16 const ORG_TOKEN: &str = "forge_org_token_for_tests_0123456789";
24 const ORG_SESSION: &str = "org-session-token-for-tests-0123456789";17 const ORG_SESSION: &str = "org-session-token-for-tests-0123456789";
25 18
26-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
27 fn admin(config: &Path, args: &[&str]) {19 fn admin(config: &Path, args: &[&str]) {
28 let out = Command::new(bin())20 let out = Command::new(bin())
29 .arg("--config")21 .arg("--config")
@@ -40,7 +32,6 @@ fn admin(config: &Path, args: &[&str]) {
40 );32 );
41 }33 }
42 34
43-/// Submits the login form for `username` with the shared password.
44 async fn try_login(http: &Http, username: &str) -> Resp {35 async fn try_login(http: &Http, username: &str) -> Resp {
45 let page = http.get("/login", None).await;36 let page = http.get("/login", None).await;
46 assert_eq!(page.status, 200, "GET /login");37 assert_eq!(page.status, 200, "GET /login");
@@ -65,8 +56,6 @@ struct Env {
65 http: Http,56 http: Http,
66 }57 }
67 58
68-/// Creates the users (`dana` is the first user, so an administrator), then runs `seed` against
69-/// the store before the server starts.
70 async fn start<F, Fut>(seed: F) -> Env59 async fn start<F, Fut>(seed: F) -> Env
71 where60 where
72 F: FnOnce(Store) -> Fut,61 F: FnOnce(Store) -> Fut,
@@ -91,8 +80,6 @@ where
91 }80 }
92 }81 }
93 82
94-/// `acme` is an org owned by tahinli, with a public repo, a session row, and an API token. None of
95-/// them may authenticate.
96 async fn seed_org(store: Store) {83 async fn seed_org(store: Store) {
97 let tahinli = store84 let tahinli = store
98 .user_by_username("tahinli")85 .user_by_username("tahinli")
crates/forge-e2e/tests/e2e/orgs_live_e2e.rsmodified+0 -28
@@ -1,7 +1,3 @@
1-//! End-to-end: the organization pages follow their change streams. The real `forge` binary runs
2-//! with a seeded org (owner tahinli, member bob, a team), and the test drives the writes over HTTP
3-//! and reads each stream. It also checks that each stream refuses the viewers its page refuses.
4-
5 use crate::common::{1 use crate::common::{
6 Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,2 Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
7 };3 };
@@ -12,13 +8,11 @@ use std::time::Duration;
12 use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings};8 use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings};
13 use forge_core::{Role, Store, Visibility};9 use forge_core::{Role, Store, Visibility};
14 10
15-/// Each test starts its own server, so the tests run one at a time.
16 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =11 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =
17 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));12 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
18 13
19 const PW: &str = "tahinli-password-123";14 const PW: &str = "tahinli-password-123";
20 15
21-/// The `data-live` value of the first element that names a stream, if any.
22 fn live_url(body: &str) -> Option<String> {16 fn live_url(body: &str) -> Option<String> {
23 let doc = scraper::Html::parse_document(body);17 let doc = scraper::Html::parse_document(body);
24 let selector = scraper::Selector::parse("[data-live]").expect("selector");18 let selector = scraper::Selector::parse("[data-live]").expect("selector");
@@ -28,7 +22,6 @@ fn live_url(body: &str) -> Option<String> {
28 .map(str::to_owned)22 .map(str::to_owned)
29 }23 }
30 24
31-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
32 fn admin(config: &Path, args: &[&str]) -> Output {25 fn admin(config: &Path, args: &[&str]) -> Output {
33 let out = Command::new(bin())26 let out = Command::new(bin())
34 .arg("--config")27 .arg("--config")
@@ -46,14 +39,12 @@ fn admin(config: &Path, args: &[&str]) -> Output {
46 out39 out
47 }40 }
48 41
49-/// The session's CSRF token, read from a page every signed-in user can open.
50 async fn csrf_for(http: &Http, session: &str) -> String {42 async fn csrf_for(http: &Http, session: &str) -> String {
51 let page = http.get("/settings/keys", Some(session)).await;43 let page = http.get("/settings/keys", Some(session)).await;
52 assert_eq!(page.status, 200, "GET /settings/keys");44 assert_eq!(page.status, 200, "GET /settings/keys");
53 input_value(&page.body, "csrf")45 input_value(&page.body, "csrf")
54 }46 }
55 47
56-/// Waits for the next event of a stream, which must be `changed`.
57 async fn next_changed(res: &mut reqwest::Response, what: &str) {48 async fn next_changed(res: &mut reqwest::Response, what: &str) {
58 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())49 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
59 .await50 .await
@@ -64,13 +55,11 @@ async fn next_changed(res: &mut reqwest::Response, what: &str) {
64 assert!(text.contains("event: changed"), "{what}: {text}");55 assert!(text.contains("event: changed"), "{what}: {text}");
65 }56 }
66 57
67-/// Asserts that nothing arrives on a stream for two seconds.
68 async fn assert_quiet(res: &mut reqwest::Response, what: &str) {58 async fn assert_quiet(res: &mut reqwest::Response, what: &str) {
69 let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await;59 let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await;
70 assert!(got.is_err(), "{what}: the stream sent an event");60 assert!(got.is_err(), "{what}: the stream sent an event");
71 }61 }
72 62
73-/// A temp dir short enough for the unix socket path limit.
74 fn short_temp_dir() -> tempfile::TempDir {63 fn short_temp_dir() -> tempfile::TempDir {
75 tempfile::Builder::new()64 tempfile::Builder::new()
76 .prefix("orgl")65 .prefix("orgl")
@@ -95,7 +84,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
95 admin(&config, &["create-user", name]);84 admin(&config, &["create-user", name]);
96 }85 }
97 86
98- // Acme is tahinli's org with bob as a member. Carol is added and dana never joins.
99 {87 {
100 let store = Store::open(&dir.join("forge.db"))88 let store = Store::open(&dir.join("forge.db"))
101 .await89 .await
@@ -120,7 +108,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
120 let dana = login(&http, "dana", PW).await;108 let dana = login(&http, "dana", PW).await;
121 let csrf = csrf_for(&http, &tahinli).await;109 let csrf = csrf_for(&http, &tahinli).await;
122 110
123- // Each page names its stream, and the stream is served at that URL.
124 let members = http.get("/org/acme/members", Some(&tahinli)).await;111 let members = http.get("/org/acme/members", Some(&tahinli)).await;
125 assert_eq!(members.status, 200, "GET members");112 assert_eq!(members.status, 200, "GET members");
126 assert_eq!(113 assert_eq!(
@@ -141,7 +128,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
141 "settings page follows its stream"128 "settings page follows its stream"
142 );129 );
143 130
144- // Owner streams: members, teams and settings all wake on a write to the org.
145 let mut members_events = http131 let mut members_events = http
146 .stream("/org/acme/members/events", Some(&tahinli))132 .stream("/org/acme/members/events", Some(&tahinli))
147 .await;133 .await;
@@ -154,7 +140,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
154 assert_eq!(settings_events.status().as_u16(), 200, "settings stream");140 assert_eq!(settings_events.status().as_u16(), 200, "settings stream");
155 assert_quiet(&mut members_events, "connecting to the members stream").await;141 assert_quiet(&mut members_events, "connecting to the members stream").await;
156 142
157- // Adding carol wakes the members stream, and the redirect carries the notice in its query.
158 let res = http143 let res = http
159 .post_form(144 .post_form(
160 "/org/acme/members/add",145 "/org/acme/members/add",
@@ -173,7 +158,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
173 let shown = http.get("/org/acme/members", Some(&tahinli)).await;158 let shown = http.get("/org/acme/members", Some(&tahinli)).await;
174 assert!(shown.body.contains("href=\"/carol\""), "carol listed");159 assert!(shown.body.contains("href=\"/carol\""), "carol listed");
175 160
176- // Creating a team wakes the teams list.
177 let res = http161 let res = http
178 .post_form(162 .post_form(
179 "/org/acme/teams/new",163 "/org/acme/teams/new",
@@ -189,7 +173,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
189 assert_eq!(res.status, 303, "create team: {}", res.body);173 assert_eq!(res.status, 303, "create team: {}", res.body);
190 next_changed(&mut teams_events, "creating a team").await;174 next_changed(&mut teams_events, "creating a team").await;
191 175
192- // Saving the settings wakes the settings stream.
193 let res = http176 let res = http
194 .post_form(177 .post_form(
195 "/org/acme/settings",178 "/org/acme/settings",
@@ -204,8 +187,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
204 assert_eq!(res.status, 303, "save settings: {}", res.body);187 assert_eq!(res.status, 303, "save settings: {}", res.body);
205 next_changed(&mut settings_events, "saving the settings").await;188 next_changed(&mut settings_events, "saving the settings").await;
206 189
207- // The notice is still in the URL after a live refresh reads the same page again, so the
208- // refreshed page shows it: a read does not use it up.
209 let location = res.location().expect("settings redirect");190 let location = res.location().expect("settings redirect");
210 let first = http.get(&location, Some(&tahinli)).await;191 let first = http.get(&location, Some(&tahinli)).await;
211 let again = http.get(&location, Some(&tahinli)).await;192 let again = http.get(&location, Some(&tahinli)).await;
@@ -218,8 +199,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
218 "notice survives a re-read"199 "notice survives a re-read"
219 );200 );
220 201
221- // Access: a non-member gets 404 on the members stream, a member who is not an owner gets 403
222- // on the settings stream, and an anonymous viewer gets no stream at all.
223 let outsider = http.stream("/org/acme/members/events", Some(&dana)).await;202 let outsider = http.stream("/org/acme/members/events", Some(&dana)).await;
224 assert_eq!(outsider.status().as_u16(), 404, "non-member members stream");203 assert_eq!(outsider.status().as_u16(), 404, "non-member members stream");
225 let outsider = http.stream("/org/acme/teams/events", Some(&dana)).await;204 let outsider = http.stream("/org/acme/teams/events", Some(&dana)).await;
@@ -232,7 +211,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
232 "anonymous members stream is refused"211 "anonymous members stream is refused"
233 );212 );
234 213
235- // Bob is a member, so he follows the members stream and sees writes to it.
236 let mut bob_members = http.stream("/org/acme/members/events", Some(&bob)).await;214 let mut bob_members = http.stream("/org/acme/members/events", Some(&bob)).await;
237 assert_eq!(bob_members.status().as_u16(), 200, "member members stream");215 assert_eq!(bob_members.status().as_u16(), 200, "member members stream");
238 let res = http216 let res = http
@@ -246,7 +224,6 @@ async fn org_pages_follow_writes_live_and_refuse_outsiders() {
246 next_changed(&mut bob_members, "adding dana").await;224 next_changed(&mut bob_members, "adding dana").await;
247 }225 }
248 226
249-/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does.
250 fn init_bare(data_dir: &Path, repo_id: &str) {227 fn init_bare(data_dir: &Path, repo_id: &str) {
251 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");228 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
252 std::fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");229 std::fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");
@@ -273,8 +250,6 @@ async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() {
273 admin(&config, &["create-user", "tahinli", "--admin"]);250 admin(&config, &["create-user", "tahinli", "--admin"]);
274 admin(&config, &["create-user", "bob"]);251 admin(&config, &["create-user", "bob"]);
275 252
276- // Acme has a private repo linked to its team "devs". Bob is an org member who is not on the
277- // team and has no default access, so he cannot read the repo. The owner can.
278 let team_id = {253 let team_id = {
279 let store = Store::open(&dir.join("forge.db"))254 let store = Store::open(&dir.join("forge.db"))
280 .await255 .await
@@ -323,7 +298,6 @@ async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() {
323 let csrf = csrf_for(&http, &tahinli).await;298 let csrf = csrf_for(&http, &tahinli).await;
324 let team_page = format!("/org/acme/teams/{team_id}");299 let team_page = format!("/org/acme/teams/{team_id}");
325 300
326- // (a) The owner sees the linked repo on the team page. Bob cannot read it, so he does not.
327 let owner_view = http.get(&team_page, Some(&tahinli)).await;301 let owner_view = http.get(&team_page, Some(&tahinli)).await;
328 assert_eq!(owner_view.status, 200, "owner team page");302 assert_eq!(owner_view.status, 200, "owner team page");
329 assert!(303 assert!(
@@ -337,8 +311,6 @@ async fn private_linked_repo_is_hidden_from_a_viewer_who_cannot_read_it() {
337 "a viewer who cannot read the repo does not see it"311 "a viewer who cannot read the repo does not see it"
338 );312 );
339 313
340- // (b) A rename of that repo wakes the owner's team stream, and bob's stays quiet: the page
341- // he sees does not change, so no refresh is sent to him.
342 let mut bob_events = http314 let mut bob_events = http
343 .stream(&format!("{team_page}/events"), Some(&bob))315 .stream(&format!("{team_page}/events"), Some(&bob))
344 .await;316 .await;
crates/forge-e2e/tests/e2e/orgs_ui_e2e.rsmodified+0 -37
@@ -1,8 +1,3 @@
1-//! Black-box tests for the organization pages: members, teams, settings, the creation policy and
2-//! the owner choice on the new repo form. They start the real `forge` binary, seed the org rows
3-//! through the store before the server starts, and then drive the pages over HTTP. Cookies are
4-//! handled by hand, as in `repo_collaborators_e2e.rs`.
5-
6 use crate::common::{1 use crate::common::{
7 Http, Resp, bin, describe, input_value, launch, launch_with, login, pick_ports, temp_dir,2 Http, Resp, bin, describe, input_value, launch, launch_with, login, pick_ports, temp_dir,
8 tool_on_path, write_config,3 tool_on_path, write_config,
@@ -15,13 +10,11 @@ use forge_core::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings};
15 use forge_core::{Role, Store, Visibility};10 use forge_core::{Role, Store, Visibility};
16 use reqwest::header::LOCATION;11 use reqwest::header::LOCATION;
17 12
18-/// Each test starts its own server, so the tests run one at a time.
19 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =13 static SERIAL: std::sync::LazyLock<tokio::sync::Mutex<()>> =
20 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));14 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
21 15
22 const PW: &str = "tahinli-password-123";16 const PW: &str = "tahinli-password-123";
23 17
24-/// The value of the selected option of the `<select name="...">` on a page.
25 fn selected_value(body: &str, name: &str) -> Option<String> {18 fn selected_value(body: &str, name: &str) -> Option<String> {
26 let doc = scraper::Html::parse_document(body);19 let doc = scraper::Html::parse_document(body);
27 let selector = scraper::Selector::parse(&format!("select[name=\"{name}\"] option[selected]"))20 let selector = scraper::Selector::parse(&format!("select[name=\"{name}\"] option[selected]"))
@@ -32,7 +25,6 @@ fn selected_value(body: &str, name: &str) -> Option<String> {
32 .map(str::to_owned)25 .map(str::to_owned)
33 }26 }
34 27
35-/// The values of every option of the owner select on the new repo form.
36 fn owner_options(body: &str) -> Vec<String> {28 fn owner_options(body: &str) -> Vec<String> {
37 let doc = scraper::Html::parse_document(body);29 let doc = scraper::Html::parse_document(body);
38 let selector = scraper::Selector::parse("select[name=\"owner\"] option").expect("selector");30 let selector = scraper::Selector::parse("select[name=\"owner\"] option").expect("selector");
@@ -41,7 +33,6 @@ fn owner_options(body: &str) -> Vec<String> {
41 .collect()33 .collect()
42 }34 }
43 35
44-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
45 fn admin(config: &Path, args: &[&str]) -> Output {36 fn admin(config: &Path, args: &[&str]) -> Output {
46 let out = Command::new(bin())37 let out = Command::new(bin())
47 .arg("--config")38 .arg("--config")
@@ -59,14 +50,12 @@ fn admin(config: &Path, args: &[&str]) -> Output {
59 out50 out
60 }51 }
61 52
62-/// The session's CSRF token, read from a page every signed-in user can open.
63 async fn csrf_for(http: &Http, session: &str) -> String {53 async fn csrf_for(http: &Http, session: &str) -> String {
64 let page = http.get("/settings/keys", Some(session)).await;54 let page = http.get("/settings/keys", Some(session)).await;
65 assert_eq!(page.status, 200, "GET /settings/keys");55 assert_eq!(page.status, 200, "GET /settings/keys");
66 input_value(&page.body, "csrf")56 input_value(&page.body, "csrf")
67 }57 }
68 58
69-/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does.
70 fn init_bare(data_dir: &Path, repo_id: &str) {59 fn init_bare(data_dir: &Path, repo_id: &str) {
71 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");60 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
72 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");61 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");
@@ -78,8 +67,6 @@ fn init_bare(data_dir: &Path, repo_id: &str) {
78 assert!(out.status.success(), "git init --bare: {}", describe(&out));67 assert!(out.status.success(), "git init --bare: {}", describe(&out));
79 }68 }
80 69
81-/// The redirect target of a write, which carries the notice in its query: the next GET of it shows the
82-/// notice.
83 fn notice_location(redirect: &Resp) -> String {70 fn notice_location(redirect: &Resp) -> String {
84 redirect.header(LOCATION).expect("notice redirect")71 redirect.header(LOCATION).expect("notice redirect")
85 }72 }
@@ -101,8 +88,6 @@ async fn org_members_teams_and_access_end_to_end() {
101 admin(&config, &["create-user", name]);88 admin(&config, &["create-user", name]);
102 }89 }
103 90
104- // Acme is tahinli's org. Bob is a member with no default access, and a team gives him read on
105- // acme's private repo. Initech is an empty org, used later for deletion.
106 let (tahinli_id, team_id) = {91 let (tahinli_id, team_id) = {
107 let store = Store::open(&dir.join("forge.db"))92 let store = Store::open(&dir.join("forge.db"))
108 .await93 .await
@@ -156,8 +141,6 @@ async fn org_members_teams_and_access_end_to_end() {
156 let dana = login(&http, "dana", PW).await;141 let dana = login(&http, "dana", PW).await;
157 let members = "/org/acme/members";142 let members = "/org/acme/members";
158 143
159- // Anonymous visitors go to login. Non-members get 404 on the org pages. Members see the list
160- // but no owner controls.
161 assert_eq!(http.get(members, None).await.status, 303, "anonymous");144 assert_eq!(http.get(members, None).await.status, 303, "anonymous");
162 assert_eq!(145 assert_eq!(
163 http.get(members, Some(&carol)).await.status,146 http.get(members, Some(&carol)).await.status,
@@ -171,7 +154,6 @@ async fn org_members_teams_and_access_end_to_end() {
171 "members get no add form"154 "members get no add form"
172 );155 );
173 156
174- // A member cannot add people. The owner adds carol, and the page shows the notice.
175 let bob_csrf = csrf_for(&http, &bob).await;157 let bob_csrf = csrf_for(&http, &bob).await;
176 let res = http158 let res = http
177 .post_form(159 .post_form(
@@ -212,7 +194,6 @@ async fn org_members_teams_and_access_end_to_end() {
212 "carol is a member now"194 "carol is a member now"
213 );195 );
214 196
215- // The last owner cannot leave. The redirect carries a notice that says why.
216 let res = http197 let res = http
217 .post_form(198 .post_form(
218 "/org/acme/members/remove",199 "/org/acme/members/remove",
@@ -230,8 +211,6 @@ async fn org_members_teams_and_access_end_to_end() {
230 shown.body211 shown.body
231 );212 );
232 213
233- // Team coverage: bob cannot see acme's private repo until he joins the devs team. Dana is not
234- // in the org and never can see it through a team.
235 assert_eq!(214 assert_eq!(
236 http.get("/acme/proj", Some(&bob)).await.status,215 http.get("/acme/proj", Some(&bob)).await.status,
237 404,216 404,
@@ -267,7 +246,6 @@ async fn org_members_teams_and_access_end_to_end() {
267 "carol is not in devs"246 "carol is not in devs"
268 );247 );
269 248
270- // Dana is not an org member, so the team refuses her.
271 let res = http249 let res = http
272 .post_form(250 .post_form(
273 &format!("{team_page}/members/add"),251 &format!("{team_page}/members/add"),
@@ -284,8 +262,6 @@ async fn org_members_teams_and_access_end_to_end() {
284 "non-member refused by the team"262 "non-member refused by the team"
285 );263 );
286 264
287- // The new repo form offers the owner's own name and the orgs it may create in. Bob may not
288- // create in acme, so acme is not offered to him, and a forged owner is refused.
289 let tahinli_new = http.get("/new", Some(&tahinli)).await;265 let tahinli_new = http.get("/new", Some(&tahinli)).await;
290 assert!(266 assert!(
291 owner_options(&tahinli_new.body).contains(&"acme".to_string()),267 owner_options(&tahinli_new.body).contains(&"acme".to_string()),
@@ -363,7 +339,6 @@ async fn org_settings_delete_and_audit_end_to_end() {
363 let root_session = login(&http, "root", PW).await;339 let root_session = login(&http, "root", PW).await;
364 let settings = "/org/acme/settings";340 let settings = "/org/acme/settings";
365 341
366- // Owners only: members get 403, non-members 404, anonymous visitors go to login.
367 assert_eq!(http.get(settings, None).await.status, 303, "anonymous");342 assert_eq!(http.get(settings, None).await.status, 303, "anonymous");
368 assert_eq!(http.get(settings, Some(&bob)).await.status, 403, "member");343 assert_eq!(http.get(settings, Some(&bob)).await.status, 403, "member");
369 assert_eq!(344 assert_eq!(
@@ -372,7 +347,6 @@ async fn org_settings_delete_and_audit_end_to_end() {
372 "outsider"347 "outsider"
373 );348 );
374 349
375- // The owner saves the description and the default role. The page shows the new values.
376 let csrf = csrf_for(&http, &tahinli).await;350 let csrf = csrf_for(&http, &tahinli).await;
377 let res = http351 let res = http
378 .post_form(352 .post_form(
@@ -402,7 +376,6 @@ async fn org_settings_delete_and_audit_end_to_end() {
402 "default role saved"376 "default role saved"
403 );377 );
404 378
405- // Deleting acme is refused while it owns a repo, and the name must be typed again.
406 let res = http379 let res = http
407 .post_form(380 .post_form(
408 "/org/acme/settings/delete",381 "/org/acme/settings/delete",
@@ -422,7 +395,6 @@ async fn org_settings_delete_and_audit_end_to_end() {
422 "acme still exists"395 "acme still exists"
423 );396 );
424 397
425- // Initech has no repos, so tahinli can delete it once she types its name.
426 let initech_settings = "/org/initech/settings";398 let initech_settings = "/org/initech/settings";
427 let res = http399 let res = http
428 .post_form(400 .post_form(
@@ -452,7 +424,6 @@ async fn org_settings_delete_and_audit_end_to_end() {
452 "initech is gone"424 "initech is gone"
453 );425 );
454 426
455- // The admin audit log holds the org actions, by their stored names.
456 let audit = http427 let audit = http
457 .get(428 .get(
458 "/admin/audit?action=org_settings_updated",429 "/admin/audit?action=org_settings_updated",
@@ -547,7 +518,6 @@ async fn org_creation_can_be_limited_to_admins() {
547 assert!(profile.body.contains("Organization"), "marked as an org");518 assert!(profile.body.contains("Organization"), "marked as an org");
548 }519 }
549 520
550-/// Git on the command line, with no credential helper and no prompts.
551 fn git(cwd: &Path, args: &[&str]) -> Output {521 fn git(cwd: &Path, args: &[&str]) -> Output {
552 Command::new("git")522 Command::new("git")
553 .current_dir(cwd)523 .current_dir(cwd)
@@ -558,7 +528,6 @@ fn git(cwd: &Path, args: &[&str]) -> Output {
558 .expect("run git")528 .expect("run git")
559 }529 }
560 530
561-/// Commits one file with a fixed identity.
562 fn commit_file(repo: &Path, name: &str, content: &str) {531 fn commit_file(repo: &Path, name: &str, content: &str) {
563 fs::write(repo.join(name), content).expect("write file");532 fs::write(repo.join(name), content).expect("write file");
564 let out = git(repo, &["add", name]);533 let out = git(repo, &["add", name]);
@@ -581,7 +550,6 @@ fn commit_file(repo: &Path, name: &str, content: &str) {
581 assert!(out.status.success(), "git commit: {}", describe(&out));550 assert!(out.status.success(), "git commit: {}", describe(&out));
582 }551 }
583 552
584-/// A new access token for the session, read from the page that shows it once.
585 async fn create_token(http: &Http, session: &str) -> String {553 async fn create_token(http: &Http, session: &str) -> String {
586 let csrf = csrf_for(http, session).await;554 let csrf = csrf_for(http, session).await;
587 let res = http555 let res = http
@@ -603,7 +571,6 @@ async fn create_token(http: &Http, session: &str) -> String {
603 .to_owned()571 .to_owned()
604 }572 }
605 573
606-/// The value of the first option of the `<select name="...">` on a page.
607 fn first_option(body: &str, name: &str) -> String {574 fn first_option(body: &str, name: &str) -> String {
608 let doc = scraper::Html::parse_document(body);575 let doc = scraper::Html::parse_document(body);
609 let selector =576 let selector =
@@ -664,7 +631,6 @@ async fn org_member_pushes_over_https_through_a_write_team() {
664 let bob = login(&http, "bob", PW).await;631 let bob = login(&http, "bob", PW).await;
665 let dana = login(&http, "dana", PW).await;632 let dana = login(&http, "dana", PW).await;
666 633
667- // Tahinli creates a private repo under acme through the new repo form.
668 let csrf = csrf_for(&http, &tahinli).await;634 let csrf = csrf_for(&http, &tahinli).await;
669 let res = http635 let res = http
670 .post_form(636 .post_form(
@@ -682,7 +648,6 @@ async fn org_member_pushes_over_https_through_a_write_team() {
682 assert_eq!(res.status, 303, "create acme/pushme: {}", res.body);648 assert_eq!(res.status, 303, "create acme/pushme: {}", res.body);
683 assert_eq!(res.header(LOCATION).as_deref(), Some("/acme/pushme"));649 assert_eq!(res.header(LOCATION).as_deref(), Some("/acme/pushme"));
684 650
685- // A write team takes the repo, and bob joins the team.
686 let res = http651 let res = http
687 .post_form(652 .post_form(
688 "/org/acme/teams/new",653 "/org/acme/teams/new",
@@ -696,7 +661,6 @@ async fn org_member_pushes_over_https_through_a_write_team() {
696 )661 )
697 .await;662 .await;
698 assert_eq!(res.status, 303, "create writers: {}", res.body);663 assert_eq!(res.status, 303, "create writers: {}", res.body);
699- // The redirect carries the notice in its query. The team's own path is what follows.
700 let location = res.header(LOCATION).expect("team location");664 let location = res.header(LOCATION).expect("team location");
701 let team_url = location.split('?').next().expect("team path").to_owned();665 let team_url = location.split('?').next().expect("team path").to_owned();
702 let team = http.get(&team_url, Some(&tahinli)).await;666 let team = http.get(&team_url, Some(&tahinli)).await;
@@ -719,7 +683,6 @@ async fn org_member_pushes_over_https_through_a_write_team() {
719 .await;683 .await;
720 assert_eq!(res.status, 303, "bob joins writers");684 assert_eq!(res.status, 303, "bob joins writers");
721 685
722- // Bob pushes over HTTPS with his token. Dana is not in the org, so her clone is refused.
723 let bob_token = create_token(&http, &bob).await;686 let bob_token = create_token(&http, &bob).await;
724 let dana_token = create_token(&http, &dana).await;687 let dana_token = create_token(&http, &dana).await;
725 let bob_url = format!(688 let bob_url = format!(
crates/forge-e2e/tests/e2e/packages_e2e.rsmodified+0 -16
@@ -1,9 +1,3 @@
1-//! Black-box tests for the Cargo package registry. They start the real `forge` binary and drive
2-//! the protocol over HTTP the way cargo does: config.json, the sparse index, the publish body, the
3-//! download, yank and unyank, plus the scope, ownership and private-package rules. Tokens and a
4-//! private package are seeded through the store before the server starts, since the web API has
5-//! no way to make a package private.
6-
7 use crate::common::{Server, bin, describe, launch, pick_ports, write_config};1 use crate::common::{Server, bin, describe, launch, pick_ports, write_config};
8 use std::io::Write;2 use std::io::Write;
9 use std::path::Path;3 use std::path::Path;
@@ -17,7 +11,6 @@ use sha2::{Digest, Sha256};
17 11
18 const PW: &str = "tahinli-password-123";12 const PW: &str = "tahinli-password-123";
19 13
20-/// The index file of `demo-crate`, which is ten letters: `de/mo/demo-crate`.
21 const DEMO_INDEX: &str = "/api/packages/tahinli/cargo/de/mo/demo-crate";14 const DEMO_INDEX: &str = "/api/packages/tahinli/cargo/de/mo/demo-crate";
22 const PUBLISH: &str = "/api/packages/tahinli/cargo/api/v1/crates/new";15 const PUBLISH: &str = "/api/packages/tahinli/cargo/api/v1/crates/new";
23 16
@@ -88,7 +81,6 @@ impl Http {
88 }81 }
89 }82 }
90 83
91-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
92 fn admin(config: &Path, args: &[&str]) {84 fn admin(config: &Path, args: &[&str]) {
93 let out = Command::new(bin())85 let out = Command::new(bin())
94 .arg("--config")86 .arg("--config")
@@ -105,14 +97,12 @@ fn admin(config: &Path, args: &[&str]) {
105 );97 );
106 }98 }
107 99
108-/// A running server. The temp dir lives as long as the test.
109 struct Env {100 struct Env {
110 _root: tempfile::TempDir,101 _root: tempfile::TempDir,
111 _server: Server,102 _server: Server,
112 http: Http,103 http: Http,
113 }104 }
114 105
115-/// Creates the users `tahinli` and `bob`, runs `seed` on the store, then starts the server.
116 async fn start<F, Fut>(seed: F) -> Env106 async fn start<F, Fut>(seed: F) -> Env
117 where107 where
118 F: FnOnce(Store) -> Fut,108 F: FnOnce(Store) -> Fut,
@@ -139,7 +129,6 @@ where
139 }129 }
140 }130 }
141 131
142-/// Stores a token for `user` with the given scopes. `token` is the plaintext cargo will send.
143 async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) {132 async fn grant(store: &Store, user: &User, scopes: &[&str], token: &str) {
144 let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect();133 let scopes: Vec<String> = scopes.iter().map(|s| (*s).to_owned()).collect();
145 store134 store
@@ -156,7 +145,6 @@ async fn user(store: &Store, name: &str) -> User {
156 .expect("user exists")145 .expect("user exists")
157 }146 }
158 147
159-/// A `.crate` file: a gzipped tarball with one package directory holding Cargo.toml and README.md.
160 fn crate_file(name: &str, version: &str, readme: &str) -> Vec<u8> {148 fn crate_file(name: &str, version: &str, readme: &str) -> Vec<u8> {
161 let mut tar_bytes = Vec::new();149 let mut tar_bytes = Vec::new();
162 {150 {
@@ -187,7 +175,6 @@ fn crate_file(name: &str, version: &str, readme: &str) -> Vec<u8> {
187 gz175 gz
188 }176 }
189 177
190-/// The publish body cargo sends: a length-prefixed JSON document, then a length-prefixed crate.
191 fn publish_body(meta: &serde_json::Value, krate: &[u8]) -> Vec<u8> {178 fn publish_body(meta: &serde_json::Value, krate: &[u8]) -> Vec<u8> {
192 let json = serde_json::to_vec(meta).expect("metadata json");179 let json = serde_json::to_vec(meta).expect("metadata json");
193 let mut body = Vec::new();180 let mut body = Vec::new();
@@ -528,8 +515,6 @@ async fn profile_tab_and_package_page_show_the_published_crate() {
528 assert!(html.contains("data-live="), "the page follows live changes");515 assert!(html.contains("data-live="), "the page follows live changes");
529 }516 }
530 517
531-/// Drives the real `cargo` binary: publishes a crate with `cargo publish`, then resolves it
532-/// from a consumer project with `cargo fetch`. Ignored by default because it runs cargo.
533 #[tokio::test]518 #[tokio::test]
534 #[ignore = "runs the real cargo binary; run with --ignored"]519 #[ignore = "runs the real cargo binary; run with --ignored"]
535 async fn real_cargo_publishes_and_fetches_from_the_registry() {520 async fn real_cargo_publishes_and_fetches_from_the_registry() {
@@ -585,7 +570,6 @@ async fn real_cargo_publishes_and_fetches_from_the_registry() {
585 assert!(fetched.contains("real-demo v0.1.0"), "{fetched}");570 assert!(fetched.contains("real-demo v0.1.0"), "{fetched}");
586 }571 }
587 572
588-/// Runs cargo with `envs` in `dir`, panics with its output on failure, and returns the output.
589 fn run_cargo(dir: &Path, args: &[&str], envs: &[(&str, &str)]) -> String {573 fn run_cargo(dir: &Path, args: &[&str], envs: &[(&str, &str)]) -> String {
590 let out = Command::new("cargo")574 let out = Command::new("cargo")
591 .args(args)575 .args(args)
crates/forge-e2e/tests/e2e/pulls_e2e.rsmodified+0 -41
@@ -1,10 +1,3 @@
1-//! End-to-end: pull requests against the real `forge` binary, with real `git` pushes.
2-//!
3-//! Each test boots `forge serve` on random ports with a temp data dir, signs in through the
4-//! `/login` form, creates tokens, and pushes over HTTPS. Pages are scraped for CSRF tokens. The
5-//! scenarios cover a same-repo merge that closes an issue, a push that updates an open pull,
6-//! a fork pull merged by squash, and a conflict that blocks the merge.
7-
8 use crate::common::{1 use crate::common::{
9 Http, Resp, Server, create_token, input_value, launch, login, pick_ports, run_admin,2 Http, Resp, Server, create_token, input_value, launch, login, pick_ports, run_admin,
10 tool_on_path, write_config,3 tool_on_path, write_config,
@@ -23,7 +16,6 @@ const REPO_PATH: &str = "/tahinli/r";
23 const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test");16 const TAHINLI: (&str, &str) = ("tahinli", "tahinli@example.test");
24 const BOB: (&str, &str) = ("bob", BOB_EMAIL);17 const BOB: (&str, &str) = ("bob", BOB_EMAIL);
25 18
26-/// Text of the first state badge on a page, e.g. `Open`, `Closed` or `Merged`.
27 fn state_badge(body: &str) -> String {19 fn state_badge(body: &str) -> String {
28 let doc = scraper::Html::parse_document(body);20 let doc = scraper::Html::parse_document(body);
29 let selector =21 let selector =
@@ -34,8 +26,6 @@ fn state_badge(body: &str) -> String {
34 .unwrap_or_default()26 .unwrap_or_default()
35 }27 }
36 28
37-/// Runs git with credential helpers disabled and extra env, returning stdout trimmed. Panics on
38-/// failure.
39 fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {29 fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {
40 let mut cmd = Command::new("git");30 let mut cmd = Command::new("git");
41 cmd.current_dir(cwd)31 cmd.current_dir(cwd)
@@ -58,7 +48,6 @@ fn git(cwd: &Path, args: &[&str]) -> String {
58 git_env(cwd, args, &[])48 git_env(cwd, args, &[])
59 }49 }
60 50
61-/// Writes `file`, commits it with `who` as author and committer, and returns the new HEAD.
62 fn commit(repo: &Path, file: &str, contents: &str, message: &str, who: (&str, &str)) -> String {51 fn commit(repo: &Path, file: &str, contents: &str, message: &str, who: (&str, &str)) -> String {
63 let (name, email) = who;52 let (name, email) = who;
64 fs::write(repo.join(file), contents).expect("write file");53 fs::write(repo.join(file), contents).expect("write file");
@@ -76,7 +65,6 @@ fn commit(repo: &Path, file: &str, contents: &str, message: &str, who: (&str, &s
76 git(repo, &["rev-parse", "HEAD"])65 git(repo, &["rev-parse", "HEAD"])
77 }66 }
78 67
79-/// Clones `url` into `into` (a path that does not exist yet) and returns it.
80 fn clone(url: &str, into: &Path) -> PathBuf {68 fn clone(url: &str, into: &Path) -> PathBuf {
81 let parent = into.parent().expect("clone target has a parent");69 let parent = into.parent().expect("clone target has a parent");
82 git(70 git(
@@ -86,12 +74,10 @@ fn clone(url: &str, into: &Path) -> PathBuf {
86 into.to_path_buf()74 into.to_path_buf()
87 }75 }
88 76
89-/// The HTTPS remote for `owner/repo`, authenticated with a token.
90 fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {77 fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
91 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")78 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
92 }79 }
93 80
94-/// The commit a remote branch points at, from `git ls-remote`.
95 fn remote_sha(dir: &Path, url: &str, branch: &str) -> String {81 fn remote_sha(dir: &Path, url: &str, branch: &str) -> String {
96 let out = git(dir, &["ls-remote", url, &format!("refs/heads/{branch}")]);82 let out = git(dir, &["ls-remote", url, &format!("refs/heads/{branch}")]);
97 out.split_whitespace()83 out.split_whitespace()
@@ -100,20 +86,17 @@ fn remote_sha(dir: &Path, url: &str, branch: &str) -> String {
100 .to_owned()86 .to_owned()
101 }87 }
102 88
103-/// Number of parents of `commit` in the repository at `dir`.
104 fn parent_count(dir: &Path, commit: &str) -> usize {89 fn parent_count(dir: &Path, commit: &str) -> usize {
105 let line = git(dir, &["rev-list", "--parents", "-n1", commit]);90 let line = git(dir, &["rev-list", "--parents", "-n1", commit]);
106 line.split_whitespace().count() - 191 line.split_whitespace().count() - 1
107 }92 }
108 93
109-/// The session's CSRF token, scraped from the token settings page.
110 async fn csrf_token(http: &Http, session: &str) -> String {94 async fn csrf_token(http: &Http, session: &str) -> String {
111 let page = http.get_cookie("/settings/keys", session).await;95 let page = http.get_cookie("/settings/keys", session).await;
112 assert_eq!(page.status, 200, "GET /settings/keys");96 assert_eq!(page.status, 200, "GET /settings/keys");
113 input_value(&page.body, "csrf")97 input_value(&page.body, "csrf")
114 }98 }
115 99
116-/// Creates a public repo `name` owned by tahinli through `/new`.
117 async fn create_repo(http: &Http, session: &str, name: &str) {100 async fn create_repo(http: &Http, session: &str, name: &str) {
118 let page = http.get_cookie("/new", session).await;101 let page = http.get_cookie("/new", session).await;
119 assert_eq!(page.status, 200, "GET /new");102 assert_eq!(page.status, 200, "GET /new");
@@ -138,8 +121,6 @@ async fn create_repo(http: &Http, session: &str, name: &str) {
138 );121 );
139 }122 }
140 123
141-/// A running server with its own temp data dir. Field order matters: the server is dropped (and
142-/// killed) before the temp dir is removed.
143 struct Booted {124 struct Booted {
144 _server: Server,125 _server: Server,
145 _root: tempfile::TempDir,126 _root: tempfile::TempDir,
@@ -148,17 +129,14 @@ struct Booted {
148 http_port: u16,129 http_port: u16,
149 }130 }
150 131
151-/// The server's stdout and stderr, for assertion messages.
152 fn server_log(b: &Booted) -> String {132 fn server_log(b: &Booted) -> String {
153 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()133 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
154 }134 }
155 135
156-/// Creates tahinli (admin) and bob, then boots the server on fresh ports.
157 async fn boot() -> Booted {136 async fn boot() -> Booted {
158 if !tool_on_path("git") {137 if !tool_on_path("git") {
159 panic!("`git` was not found on PATH");138 panic!("`git` was not found on PATH");
160 }139 }
161- // Keep the path short: the internal unix socket path is limited to 108 bytes.
162 let root = tempfile::Builder::new()140 let root = tempfile::Builder::new()
163 .prefix("pr2e")141 .prefix("pr2e")
164 .tempdir_in("/tmp")142 .tempdir_in("/tmp")
@@ -179,7 +157,6 @@ async fn boot() -> Booted {
179 }157 }
180 }158 }
181 159
182-/// Creates `tahinli/r` with `main` pushed as tahinli, and returns tahinli's session and token.
183 async fn tahinli_repo_with_main(b: &Booted) -> (String, String, PathBuf) {160 async fn tahinli_repo_with_main(b: &Booted) -> (String, String, PathBuf) {
184 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;161 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
185 let token = create_token(&b.http, &tahinli, "pulls-token").await;162 let token = create_token(&b.http, &tahinli, "pulls-token").await;
@@ -193,7 +170,6 @@ async fn tahinli_repo_with_main(b: &Booted) -> (String, String, PathBuf) {
193 (tahinli, token, work)170 (tahinli, token, work)
194 }171 }
195 172
196-/// Opens a pull request `base...head` on tahinli/r through the compare form. Returns its number.
197 async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &str) -> u32 {173 async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &str) -> u32 {
198 let compare = http174 let compare = http
199 .get_cookie(&format!("{REPO_PATH}/compare/{base}...{head}"), session)175 .get_cookie(&format!("{REPO_PATH}/compare/{base}...{head}"), session)
@@ -222,7 +198,6 @@ async fn open_pull(http: &Http, session: &str, base: &str, head: &str, title: &s
222 .unwrap_or_else(|| panic!("no pull number in {location}"))198 .unwrap_or_else(|| panic!("no pull number in {location}"))
223 }199 }
224 200
225-/// Creates an issue on tahinli/r through the web form. Returns its number.
226 async fn open_issue(http: &Http, session: &str, title: &str) -> u32 {201 async fn open_issue(http: &Http, session: &str, title: &str) -> u32 {
227 let page = http202 let page = http
228 .get_cookie(&format!("{REPO_PATH}/issues/new"), session)203 .get_cookie(&format!("{REPO_PATH}/issues/new"), session)
@@ -245,7 +220,6 @@ async fn open_issue(http: &Http, session: &str, title: &str) -> u32 {
245 .unwrap_or_else(|| panic!("no issue number in {location}"))220 .unwrap_or_else(|| panic!("no issue number in {location}"))
246 }221 }
247 222
248-/// Polls `path` until `done` accepts the body, failing after 10 seconds.
249 async fn wait_page(223 async fn wait_page(
250 http: &Http,224 http: &Http,
251 session: &str,225 session: &str,
@@ -268,7 +242,6 @@ async fn wait_page(
268 }242 }
269 }243 }
270 244
271-/// Posts a merge for pull `number` with `style` as `session`.
272 async fn merge(http: &Http, session: &str, number: u32, style: &str) -> Resp {245 async fn merge(http: &Http, session: &str, number: u32, style: &str) -> Resp {
273 let csrf = csrf_token(http, session).await;246 let csrf = csrf_token(http, session).await;
274 http.post_form(247 http.post_form(
@@ -378,14 +351,12 @@ async fn push_to_head_branch_updates_open_pull() {
378 assert!(commits.body.contains(&second[..7]), "new commit sha shown");351 assert!(commits.body.contains(&second[..7]), "new commit sha shown");
379 }352 }
380 353
381-/// Opens a live stream, as `session` or anonymously.
382 async fn open_stream(http: &Http, path: &str, session: Option<&str>) -> reqwest::Response {354 async fn open_stream(http: &Http, path: &str, session: Option<&str>) -> reqwest::Response {
383 let mut req = http.client.get(format!("{}{path}", http.base));355 let mut req = http.client.get(format!("{}{path}", http.base));
384 if let Some(session) = session {356 if let Some(session) = session {
385 req = req.header(COOKIE, session);357 req = req.header(COOKIE, session);
386 }358 }
387 let mut res = req.send().await.expect("stream request");359 let mut res = req.send().await.expect("stream request");
388- // A stream that opens sends its `retry` field first. It is not an event, so it is read here.
389 if res.status().is_success() {360 if res.status().is_success() {
390 let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk())361 let retry = tokio::time::timeout(Duration::from_secs(5), res.chunk())
391 .await362 .await
@@ -397,7 +368,6 @@ async fn open_stream(http: &Http, path: &str, session: Option<&str>) -> reqwest:
397 res368 res
398 }369 }
399 370
400-/// Waits for the next event of a stream, which must be `changed`.
401 async fn next_changed(res: &mut reqwest::Response, what: &str) {371 async fn next_changed(res: &mut reqwest::Response, what: &str) {
402 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())372 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
403 .await373 .await
@@ -408,7 +378,6 @@ async fn next_changed(res: &mut reqwest::Response, what: &str) {
408 assert!(text.contains("event: changed"), "{what}: {text}");378 assert!(text.contains("event: changed"), "{what}: {text}");
409 }379 }
410 380
411-/// Asserts that nothing arrives on a stream for two seconds.
412 async fn assert_quiet(res: &mut reqwest::Response, what: &str) {381 async fn assert_quiet(res: &mut reqwest::Response, what: &str) {
413 let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await;382 let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await;
414 assert!(got.is_err(), "{what}: the stream sent an event");383 assert!(got.is_err(), "{what}: the stream sent an event");
@@ -426,7 +395,6 @@ async fn pull_pages_follow_writes_live() {
426 let pull = format!("{REPO_PATH}/pulls/{number}");395 let pull = format!("{REPO_PATH}/pulls/{number}");
427 let list = format!("{REPO_PATH}/pulls");396 let list = format!("{REPO_PATH}/pulls");
428 397
429- // The pull page and the list render the streams they follow.
430 let page = b.http.get_cookie(&pull, &tahinli).await;398 let page = b.http.get_cookie(&pull, &tahinli).await;
431 assert_eq!(page.status, 200, "GET pull");399 assert_eq!(page.status, 200, "GET pull");
432 assert!(400 assert!(
@@ -447,7 +415,6 @@ async fn pull_pages_follow_writes_live() {
447 assert_eq!(list_events.status().as_u16(), 200, "list stream");415 assert_eq!(list_events.status().as_u16(), 200, "list stream");
448 assert_quiet(&mut pull_events, "connecting to the pull stream").await;416 assert_quiet(&mut pull_events, "connecting to the pull stream").await;
449 417
450- // A comment on the conversation wakes both the pull and the list.
451 let csrf = csrf_token(&b.http, &tahinli).await;418 let csrf = csrf_token(&b.http, &tahinli).await;
452 let res = b419 let res = b
453 .http420 .http
@@ -465,7 +432,6 @@ async fn pull_pages_follow_writes_live() {
465 next_changed(&mut pull_events, "a comment").await;432 next_changed(&mut pull_events, "a comment").await;
466 next_changed(&mut list_events, "a comment").await;433 next_changed(&mut list_events, "a comment").await;
467 434
468- // A review submitted on the head.
469 let csrf = csrf_token(&b.http, &tahinli).await;435 let csrf = csrf_token(&b.http, &tahinli).await;
470 let res = b436 let res = b
471 .http437 .http
@@ -483,13 +449,11 @@ async fn pull_pages_follow_writes_live() {
483 assert_eq!(res.status, 303, "review: {}", res.body);449 assert_eq!(res.status, 303, "review: {}", res.body);
484 next_changed(&mut pull_events, "a review").await;450 next_changed(&mut pull_events, "a review").await;
485 451
486- // A push to the head branch updates the pull and the list.
487 let second = commit(&work, "second.txt", "2\n", "second on live", TAHINLI);452 let second = commit(&work, "second.txt", "2\n", "second on live", TAHINLI);
488 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]);453 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]);
489 next_changed(&mut pull_events, "a push to the head").await;454 next_changed(&mut pull_events, "a push to the head").await;
490 next_changed(&mut list_events, "a push to the head").await;455 next_changed(&mut list_events, "a push to the head").await;
491 456
492- // A commit status for the head commit (what CI reports) changes the pull.
493 let status = b457 let status = b
494 .http458 .http
495 .client459 .client
@@ -506,13 +470,11 @@ async fn pull_pages_follow_writes_live() {
506 assert_eq!(status.status().as_u16(), 201, "status posted");470 assert_eq!(status.status().as_u16(), 201, "status posted");
507 next_changed(&mut pull_events, "a commit status on the head").await;471 next_changed(&mut pull_events, "a commit status on the head").await;
508 472
509- // Merging the pull changes it, and the list.
510 let res = merge(&b.http, &tahinli, number, "merge").await;473 let res = merge(&b.http, &tahinli, number, "merge").await;
511 assert_eq!(res.status, 303, "merge: {}", res.body);474 assert_eq!(res.status, 303, "merge: {}", res.body);
512 next_changed(&mut pull_events, "the merge").await;475 next_changed(&mut pull_events, "the merge").await;
513 next_changed(&mut list_events, "the merge").await;476 next_changed(&mut list_events, "the merge").await;
514 477
515- // A private repo streams only to a viewer who can read it.
516 let csrf = csrf_token(&b.http, &tahinli).await;478 let csrf = csrf_token(&b.http, &tahinli).await;
517 let res = b479 let res = b
518 .http480 .http
@@ -545,7 +507,6 @@ async fn fork_pull_squash_merge_credits_contributor() {
545 let bob = login(&b.http, "bob", BOB_PW).await;507 let bob = login(&b.http, "bob", BOB_PW).await;
546 let bob_token = create_token(&b.http, &bob, "bob-token").await;508 let bob_token = create_token(&b.http, &bob, "bob-token").await;
547 509
548- // Bob forks tahinli/r. The fork keeps the source name under bob's owner.
549 let csrf = csrf_token(&b.http, &bob).await;510 let csrf = csrf_token(&b.http, &bob).await;
550 let fork = b511 let fork = b
551 .http512 .http
@@ -565,7 +526,6 @@ async fn fork_pull_squash_merge_credits_contributor() {
565 526
566 let number = open_pull(&b.http, &bob, "main", "bob:bob-feature", "Bob change").await;527 let number = open_pull(&b.http, &bob, "main", "bob:bob-feature", "Bob change").await;
567 528
568- // Bob can open the pull but cannot merge it.
569 let denied = merge(&b.http, &bob, number, "merge").await;529 let denied = merge(&b.http, &bob, number, "merge").await;
570 assert_eq!(denied.status, 403, "bob must not merge");530 assert_eq!(denied.status, 403, "bob must not merge");
571 531
@@ -589,7 +549,6 @@ async fn conflicting_pull_cannot_merge() {
589 let b = boot().await;549 let b = boot().await;
590 let (tahinli, token, work) = tahinli_repo_with_main(&b).await;550 let (tahinli, token, work) = tahinli_repo_with_main(&b).await;
591 551
592- // Both sides edit the same line. The pull is opened while main still matches its base.
593 git(&work, &["checkout", "-q", "-b", "conflict"]);552 git(&work, &["checkout", "-q", "-b", "conflict"]);
594 commit(&work, "shared.txt", "branch side\n", "branch edit", TAHINLI);553 commit(&work, "shared.txt", "branch side\n", "branch edit", TAHINLI);
595 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/conflict"]);554 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/conflict"]);
crates/forge-e2e/tests/e2e/repo_collaborators_e2e.rsmodified+0 -24
@@ -1,7 +1,3 @@
1-//! Black-box tests for the collaborators settings page. They start the real `forge` binary,
2-//! seed users and repos through the store before the server starts, and then drive the page and
3-//! its POST forms over HTTP. Cookies are handled by hand (see `repo_settings_e2e.rs`).
4-
5 use crate::common::{1 use crate::common::{
6 Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, with_cookie,2 Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, with_cookie,
7 write_config,3 write_config,
@@ -15,7 +11,6 @@ use reqwest::header::LOCATION;
15 11
16 const PW: &str = "tahinli-password-123";12 const PW: &str = "tahinli-password-123";
17 13
18-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
19 fn admin(config: &Path, args: &[&str]) -> Output {14 fn admin(config: &Path, args: &[&str]) -> Output {
20 let out = Command::new(bin())15 let out = Command::new(bin())
21 .arg("--config")16 .arg("--config")
@@ -33,14 +28,12 @@ fn admin(config: &Path, args: &[&str]) -> Output {
33 out28 out
34 }29 }
35 30
36-/// The session's CSRF token, read from a page every signed-in user can open.
37 async fn csrf_for(http: &Http, session: &str) -> String {31 async fn csrf_for(http: &Http, session: &str) -> String {
38 let page = http.get("/settings/keys", Some(session)).await;32 let page = http.get("/settings/keys", Some(session)).await;
39 assert_eq!(page.status, 200, "GET /settings/keys");33 assert_eq!(page.status, 200, "GET /settings/keys");
40 input_value(&page.body, "csrf")34 input_value(&page.body, "csrf")
41 }35 }
42 36
43-/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does.
44 fn init_bare(data_dir: &Path, repo_id: &str) {37 fn init_bare(data_dir: &Path, repo_id: &str) {
45 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");38 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
46 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");39 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");
@@ -52,7 +45,6 @@ fn init_bare(data_dir: &Path, repo_id: &str) {
52 assert!(out.status.success(), "git init --bare: {}", describe(&out));45 assert!(out.status.success(), "git init --bare: {}", describe(&out));
53 }46 }
54 47
55-/// The role the page shows as selected for `username`, or `None` when they have no row.
56 async fn shown_role(http: &Http, session: &str, username: &str) -> Option<String> {48 async fn shown_role(http: &Http, session: &str, username: &str) -> Option<String> {
57 let page = http49 let page = http
58 .get("/olivia/priv/settings/collaborators", Some(session))50 .get("/olivia/priv/settings/collaborators", Some(session))
@@ -76,7 +68,6 @@ async fn repo_collaborators_end_to_end() {
76 return;68 return;
77 }69 }
78 70
79- // Keep the path short: the data dir holds a unix socket with a length limit.
80 let root = tempfile::Builder::new()71 let root = tempfile::Builder::new()
81 .prefix("frc")72 .prefix("frc")
82 .tempdir_in("/tmp")73 .tempdir_in("/tmp")
@@ -86,8 +77,6 @@ async fn repo_collaborators_end_to_end() {
86 let ports = pick_ports();77 let ports = pick_ports();
87 let config = write_config(&dir, ports);78 let config = write_config(&dir, ports);
88 79
89- // Olivia owns the private repo. Carol is an Admin collaborator, wendy a Write collaborator, and
90- // bob and dana are plain users who get added through the page.
91 admin(&config, &["create-user", "root", "--admin"]);80 admin(&config, &["create-user", "root", "--admin"]);
92 for name in ["olivia", "bob", "carol", "dana", "wendy"] {81 for name in ["olivia", "bob", "carol", "dana", "wendy"] {
93 admin(&config, &["create-user", name]);82 admin(&config, &["create-user", name]);
@@ -142,7 +131,6 @@ async fn repo_collaborators_end_to_end() {
142 let role = "/olivia/priv/settings/collaborators/role";131 let role = "/olivia/priv/settings/collaborators/role";
143 let remove = "/olivia/priv/settings/collaborators/remove";132 let remove = "/olivia/priv/settings/collaborators/remove";
144 133
145- // Before the add, bob cannot see the private repo or its settings.
146 assert_eq!(http.get(page, None).await.status, 404, "anonymous page");134 assert_eq!(http.get(page, None).await.status, 404, "anonymous page");
147 assert_eq!(135 assert_eq!(
148 http.get(page, Some(&bob)).await.status,136 http.get(page, Some(&bob)).await.status,
@@ -154,7 +142,6 @@ async fn repo_collaborators_end_to_end() {
154 let owner_page = http.get(page, Some(&olivia)).await;142 let owner_page = http.get(page, Some(&olivia)).await;
155 assert_eq!(owner_page.status, 200, "owner page");143 assert_eq!(owner_page.status, 200, "owner page");
156 144
157- // The owner adds bob as Write: bob now sees the private repo, and the row shows the role.
158 let csrf = csrf_for(&http, &olivia).await;145 let csrf = csrf_for(&http, &olivia).await;
159 let res = http146 let res = http
160 .post_form(147 .post_form(
@@ -174,14 +161,12 @@ async fn repo_collaborators_end_to_end() {
174 shown_role(&http, &olivia, "bob").await.as_deref(),161 shown_role(&http, &olivia, "bob").await.as_deref(),
175 Some("write")162 Some("write")
176 );163 );
177- // A Write collaborator cannot open the settings page.
178 assert_eq!(164 assert_eq!(
179 http.get(page, Some(&bob)).await.status,165 http.get(page, Some(&bob)).await.status,
180 403,166 403,
181 "write on page"167 "write on page"
182 );168 );
183 169
184- // Changing bob's role to Read through the role form.
185 let res = http170 let res = http
186 .post_form(171 .post_form(
187 role,172 role,
@@ -200,7 +185,6 @@ async fn repo_collaborators_end_to_end() {
200 "read still sees repo"185 "read still sees repo"
201 );186 );
202 187
203- // Re-adding through the add form updates the role instead of duplicating the row.
204 let res = http188 let res = http
205 .post_form(189 .post_form(
206 add,190 add,
@@ -214,7 +198,6 @@ async fn repo_collaborators_end_to_end() {
214 Some("triage")198 Some("triage")
215 );199 );
216 200
217- // Removing bob: the repo is hidden from him again.
218 let res = http201 let res = http
219 .post_form(202 .post_form(
220 remove,203 remove,
@@ -234,7 +217,6 @@ async fn repo_collaborators_end_to_end() {
234 "bob row after remove"217 "bob row after remove"
235 );218 );
236 219
237- // Notices: an unknown user and the owner both show an error on the next page view.
238 let res = http220 let res = http
239 .post_form(221 .post_form(
240 add,222 add,
@@ -273,7 +255,6 @@ async fn repo_collaborators_end_to_end() {
273 "owner notice missing"255 "owner notice missing"
274 );256 );
275 257
276- // A bad CSRF token is rejected and changes nothing.
277 let res = http258 let res = http
278 .post_form(259 .post_form(
279 add,260 add,
@@ -292,7 +273,6 @@ async fn repo_collaborators_end_to_end() {
292 "CSRF failure added bob"273 "CSRF failure added bob"
293 );274 );
294 275
295- // The Admin collaborator carol can add Read, but cannot grant Admin or change an Admin.
296 let carol_csrf = csrf_for(&http, &carol).await;276 let carol_csrf = csrf_for(&http, &carol).await;
297 assert_eq!(http.get(page, Some(&carol)).await.status, 200, "carol page");277 assert_eq!(http.get(page, Some(&carol)).await.status, 200, "carol page");
298 let res = http278 let res = http
@@ -343,7 +323,6 @@ async fn repo_collaborators_end_to_end() {
343 Some("read")323 Some("read")
344 );324 );
345 325
346- // The owner grants Admin to dana. Now carol cannot remove or demote an Admin.
347 let res = http326 let res = http
348 .post_form(327 .post_form(
349 add,328 add,
@@ -356,7 +335,6 @@ async fn repo_collaborators_end_to_end() {
356 shown_role(&http, &olivia, "dana").await.as_deref(),335 shown_role(&http, &olivia, "dana").await.as_deref(),
357 Some("admin")336 Some("admin")
358 );337 );
359- // Carol cannot remove an Admin, and cannot demote one through the role form.
360 let res = http338 let res = http
361 .post_form(339 .post_form(
362 remove,340 remove,
@@ -397,7 +375,6 @@ async fn repo_collaborators_end_to_end() {
397 "non-collaborator role change gives a notice, not a grant"375 "non-collaborator role change gives a notice, not a grant"
398 );376 );
399 377
400- // Wendy (Write) is re-added as Read through the add form.
401 let res = http378 let res = http
402 .post_form(379 .post_form(
403 add,380 add,
@@ -416,7 +393,6 @@ async fn repo_collaborators_end_to_end() {
416 "read on page"393 "read on page"
417 );394 );
418 395
419- // Carol may remove herself. The redirect goes to the repo home, and she loses the repo.
420 let res = http396 let res = http
421 .post_form(397 .post_form(
422 remove,398 remove,
crates/forge-e2e/tests/e2e/repo_rename_e2e.rsmodified+0 -31
@@ -1,10 +1,3 @@
1-//! Black-box test for rename and transfer. It seeds users and repos through the store, starts the
2-//! real `forge` binary, and drives the rename/transfer forms, the redirects, and the git clone
3-//! URLs of the old names over HTTP.
4-//!
5-//! Cookies are handled by hand because the session cookie is `__Host-forge_session` with `Secure`,
6-//! which a cookie jar would not send over plain http.
7-
8 use crate::common::{1 use crate::common::{
9 Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,2 Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
10 };3 };
@@ -17,7 +10,6 @@ use reqwest::header::LOCATION;
17 10
18 const PW: &str = "tahinli-password-123";11 const PW: &str = "tahinli-password-123";
19 12
20-/// The `action` of the first form on a page whose action ends with `suffix`.
21 fn form_action(body: &str, suffix: &str) -> String {13 fn form_action(body: &str, suffix: &str) -> String {
22 let doc = scraper::Html::parse_document(body);14 let doc = scraper::Html::parse_document(body);
23 let selector = scraper::Selector::parse("form").expect("selector");15 let selector = scraper::Selector::parse("form").expect("selector");
@@ -28,7 +20,6 @@ fn form_action(body: &str, suffix: &str) -> String {
28 .to_owned()20 .to_owned()
29 }21 }
30 22
31-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
32 fn admin(config: &Path, args: &[&str]) {23 fn admin(config: &Path, args: &[&str]) {
33 let out = Command::new(bin())24 let out = Command::new(bin())
34 .arg("--config")25 .arg("--config")
@@ -45,14 +36,12 @@ fn admin(config: &Path, args: &[&str]) {
45 );36 );
46 }37 }
47 38
48-/// The session's CSRF token, read from a page every signed-in user can open.
49 async fn csrf_for(http: &Http, session: &str) -> String {39 async fn csrf_for(http: &Http, session: &str) -> String {
50 let page = http.get("/settings/keys", Some(session)).await;40 let page = http.get("/settings/keys", Some(session)).await;
51 assert_eq!(page.status, 200, "GET /settings/keys");41 assert_eq!(page.status, 200, "GET /settings/keys");
52 input_value(&page.body, "csrf")42 input_value(&page.body, "csrf")
53 }43 }
54 44
55-/// Creates an access token through `/settings/tokens` and returns the token shown once.
56 async fn create_token(http: &Http, session: &str, name: &str) -> String {45 async fn create_token(http: &Http, session: &str, name: &str) -> String {
57 let csrf = csrf_for(http, session).await;46 let csrf = csrf_for(http, session).await;
58 let res = http47 let res = http
@@ -76,7 +65,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String {
76 token65 token
77 }66 }
78 67
79-/// Creates a public repo for the signed-in user through `/new`. Returns the response.
80 async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp {68 async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp {
81 let page = http.get("/new", Some(session)).await;69 let page = http.get("/new", Some(session)).await;
82 assert_eq!(page.status, 200, "GET /new");70 assert_eq!(page.status, 200, "GET /new");
@@ -95,7 +83,6 @@ async fn create_repo_web(http: &Http, session: &str, name: &str) -> Resp {
95 .await83 .await
96 }84 }
97 85
98-/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does.
99 fn init_bare(data_dir: &Path, repo_id: &str) {86 fn init_bare(data_dir: &Path, repo_id: &str) {
100 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");87 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
101 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");88 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");
@@ -125,7 +112,6 @@ fn path_str(path: &Path) -> &str {
125 path.to_str().expect("utf-8 path")112 path.to_str().expect("utf-8 path")
126 }113 }
127 114
128-/// Writes a file under `repo` (creating its directory) and commits it as `bob`.
129 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {115 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {
130 let file = repo.join(name);116 let file = repo.join(name);
131 fs::create_dir_all(file.parent().expect("parent")).expect("create dir");117 fs::create_dir_all(file.parent().expect("parent")).expect("create dir");
@@ -152,7 +138,6 @@ async fn repo_rename_end_to_end() {
152 return;138 return;
153 }139 }
154 140
155- // Keep the path short: the data dir holds a unix socket with a length limit.
156 let root = tempfile::Builder::new()141 let root = tempfile::Builder::new()
157 .prefix("frn")142 .prefix("frn")
158 .tempdir_in("/tmp")143 .tempdir_in("/tmp")
@@ -161,8 +146,6 @@ async fn repo_rename_end_to_end() {
161 let ports = pick_ports();146 let ports = pick_ports();
162 let config = write_config(&dir, ports);147 let config = write_config(&dir, ports);
163 148
164- // Tahinli is the instance admin. Bob owns the repos. Carol has Write on `pub` and Dave has Admin
165- // on it. Eve is an unrelated signed-in user.
166 admin(&config, &["create-user", "tahinli", "--admin"]);149 admin(&config, &["create-user", "tahinli", "--admin"]);
167 for name in ["bob", "carol", "dave", "eve"] {150 for name in ["bob", "carol", "dave", "eve"] {
168 admin(&config, &["create-user", name]);151 admin(&config, &["create-user", name]);
@@ -211,7 +194,6 @@ async fn repo_rename_end_to_end() {
211 let eve = login(&http, "eve", PW).await;194 let eve = login(&http, "eve", PW).await;
212 let bob_token = create_token(&http, &bob, "rename-e2e").await;195 let bob_token = create_token(&http, &bob, "rename-e2e").await;
213 196
214- // Bob pushes a commit with a `src` directory to the public repo, so the tree path can be checked.
215 let bob_url = |name: &str| {197 let bob_url = |name: &str| {
216 format!(198 format!(
217 "http://bob:{bob_token}@127.0.0.1:{}/bob/{name}.git",199 "http://bob:{bob_token}@127.0.0.1:{}/bob/{name}.git",
@@ -231,7 +213,6 @@ async fn repo_rename_end_to_end() {
231 let tree = http.get("/bob/pub/tree/main/src", None).await;213 let tree = http.get("/bob/pub/tree/main/src", None).await;
232 assert_eq!(tree.status, 200, "tree before rename");214 assert_eq!(tree.status, 200, "tree before rename");
233 215
234- // Bob renames `pub` to `newpub`. The form sends him to the new settings URL.
235 let csrf = csrf_for(&http, &bob).await;216 let csrf = csrf_for(&http, &bob).await;
236 let renamed = http217 let renamed = http
237 .post_form(218 .post_form(
@@ -250,7 +231,6 @@ async fn repo_rename_end_to_end() {
250 200231 200
251 );232 );
252 233
253- // The old web URL 307s to the same path under the new name, and keeps the query.
254 let old_tree = http.get("/bob/pub/tree/main/src", None).await;234 let old_tree = http.get("/bob/pub/tree/main/src", None).await;
255 assert_eq!(old_tree.status, 307, "old tree URL");235 assert_eq!(old_tree.status, 307, "old tree URL");
256 assert_eq!(236 assert_eq!(
@@ -275,7 +255,6 @@ async fn repo_rename_end_to_end() {
275 Some("/bob/newpub")255 Some("/bob/newpub")
276 );256 );
277 257
278- // The old clone URL still fetches and pushes over HTTPS.
279 ok(258 ok(
280 &git(&work, &["remote", "set-url", "origin", &bob_url("pub")]),259 &git(&work, &["remote", "set-url", "origin", &bob_url("pub")]),
281 "set old remote",260 "set old remote",
@@ -308,7 +287,6 @@ async fn repo_rename_end_to_end() {
308 );287 );
309 assert!(new_clone.join("src/lib.rs").exists());288 assert!(new_clone.join("src/lib.rs").exists());
310 289
311- // A name taken by another repo, and an invalid name, are rejected and change nothing.
312 let csrf = csrf_for(&http, &bob).await;290 let csrf = csrf_for(&http, &bob).await;
313 let taken = http291 let taken = http
314 .post_form(292 .post_form(
@@ -334,7 +312,6 @@ async fn repo_rename_end_to_end() {
334 "name unchanged after rejected renames"312 "name unchanged after rejected renames"
335 );313 );
336 314
337- // A Write collaborator cannot rename (403) and the name stays.
338 let carol_csrf = csrf_for(&http, &carol).await;315 let carol_csrf = csrf_for(&http, &carol).await;
339 let carol_rename = http316 let carol_rename = http
340 .post_form(317 .post_form(
@@ -346,7 +323,6 @@ async fn repo_rename_end_to_end() {
346 assert_eq!(carol_rename.status, 403, "write collaborator rename");323 assert_eq!(carol_rename.status, 403, "write collaborator rename");
347 assert_eq!(http.get("/bob/newpub", None).await.status, 200);324 assert_eq!(http.get("/bob/newpub", None).await.status, 200);
348 325
349- // An Admin collaborator cannot transfer (403). The repo stays with bob.
350 let dave_csrf = csrf_for(&http, &dave).await;326 let dave_csrf = csrf_for(&http, &dave).await;
351 let dave_transfer = http327 let dave_transfer = http
352 .post_form(328 .post_form(
@@ -362,7 +338,6 @@ async fn repo_rename_end_to_end() {
362 assert_eq!(dave_transfer.status, 403, "admin collaborator transfer");338 assert_eq!(dave_transfer.status, 403, "admin collaborator transfer");
363 assert_eq!(http.get("/bob/newpub", None).await.status, 200);339 assert_eq!(http.get("/bob/newpub", None).await.status, 200);
364 340
365- // Bob transfers the repo to carol. The URL moves to carol, the old one redirects.
366 let csrf = csrf_for(&http, &bob).await;341 let csrf = csrf_for(&http, &bob).await;
367 let transfer_wrong = http342 let transfer_wrong = http
368 .post_form(343 .post_form(
@@ -388,7 +363,6 @@ async fn repo_rename_end_to_end() {
388 Some(&bob),363 Some(&bob),
389 )364 )
390 .await;365 .await;
391- // The owner only offers the repo: it stays with bob until carol accepts in her inbox.
392 assert_eq!(transfer.status, 303, "transfer offered: {}", transfer.body);366 assert_eq!(transfer.status, 303, "transfer offered: {}", transfer.body);
393 assert_eq!(367 assert_eq!(
394 transfer.header(LOCATION).as_deref(),368 transfer.header(LOCATION).as_deref(),
@@ -426,8 +400,6 @@ async fn repo_rename_end_to_end() {
426 Some("/carol/newpub/tree/main/src")400 Some("/carol/newpub/tree/main/src")
427 );401 );
428 402
429- // A chain: bob/pub -> bob/newpub -> carol/newpub. The oldest name still redirects, and its
430- // clone URL still works for an anonymous fetch of this public repo.
431 let chained = http.get("/bob/pub/tree/main/src", None).await;403 let chained = http.get("/bob/pub/tree/main/src", None).await;
432 assert_eq!(chained.status, 307, "chained redirect");404 assert_eq!(chained.status, 307, "chained redirect");
433 assert_eq!(405 assert_eq!(
@@ -448,7 +420,6 @@ async fn repo_rename_end_to_end() {
448 );420 );
449 assert!(anon_clone.join("src/main.rs").exists());421 assert!(anon_clone.join("src/main.rs").exists());
450 422
451- // A new repo created with an old name takes over: no redirect, the new repo is served.
452 let takeover = create_repo_web(&http, &bob, "pub").await;423 let takeover = create_repo_web(&http, &bob, "pub").await;
453 assert_eq!(takeover.status, 303, "create pub again: {}", takeover.body);424 assert_eq!(takeover.status, 303, "create pub again: {}", takeover.body);
454 assert_eq!(takeover.header(LOCATION).as_deref(), Some("/bob/pub"));425 assert_eq!(takeover.header(LOCATION).as_deref(), Some("/bob/pub"));
@@ -460,7 +431,6 @@ async fn repo_rename_end_to_end() {
460 "the other old name still redirects"431 "the other old name still redirects"
461 );432 );
462 433
463- // A private repo renamed away: an anonymous or unrelated viewer gets 404, the owner gets 307.
464 let csrf = csrf_for(&http, &bob).await;434 let csrf = csrf_for(&http, &bob).await;
465 let secret_rename = http435 let secret_rename = http
466 .post_form(436 .post_form(
@@ -484,7 +454,6 @@ async fn repo_rename_end_to_end() {
484 let owner_view = http.get("/bob/secret", Some(&bob)).await;454 let owner_view = http.get("/bob/secret", Some(&bob)).await;
485 assert_eq!(owner_view.status, 307, "owner follows the redirect");455 assert_eq!(owner_view.status, 307, "owner follows the redirect");
486 assert_eq!(owner_view.header(LOCATION).as_deref(), Some("/bob/secret2"));456 assert_eq!(owner_view.header(LOCATION).as_deref(), Some("/bob/secret2"));
487- // Git clients get the same answer for a hidden repo as for a missing one.
488 let hidden_git = http457 let hidden_git = http
489 .get("/bob/secret.git/info/refs?service=git-upload-pack", None)458 .get("/bob/secret.git/info/refs?service=git-upload-pack", None)
490 .await;459 .await;
crates/forge-e2e/tests/e2e/repo_transfer_e2e.rsmodified+0 -19
@@ -1,10 +1,3 @@
1-//! Black-box test for repo transfer acceptance. It seeds users, repos and an org through the store,
2-//! starts the real `forge` binary, and drives the offer, decline, cancel and org-target flows over
3-//! HTTP. The target of a private repo can act only from the inbox, which this test relies on.
4-//!
5-//! Cookies are handled by hand because the session cookie is `__Host-forge_session` with `Secure`,
6-//! which a cookie jar would not send over plain http.
7-
8 use crate::common::{1 use crate::common::{
9 Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,2 Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
10 };3 };
@@ -17,7 +10,6 @@ use reqwest::header::LOCATION;
17 10
18 const PW: &str = "tahinli-password-123";11 const PW: &str = "tahinli-password-123";
19 12
20-/// The `action` of the first form on a page whose action ends with `suffix`. Panics when none.
21 fn form_action(body: &str, suffix: &str) -> String {13 fn form_action(body: &str, suffix: &str) -> String {
22 let doc = scraper::Html::parse_document(body);14 let doc = scraper::Html::parse_document(body);
23 let selector = scraper::Selector::parse("form").expect("selector");15 let selector = scraper::Selector::parse("form").expect("selector");
@@ -28,7 +20,6 @@ fn form_action(body: &str, suffix: &str) -> String {
28 .to_owned()20 .to_owned()
29 }21 }
30 22
31-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
32 fn admin(config: &std::path::Path, args: &[&str]) {23 fn admin(config: &std::path::Path, args: &[&str]) {
33 let out = Command::new(bin())24 let out = Command::new(bin())
34 .arg("--config")25 .arg("--config")
@@ -45,14 +36,12 @@ fn admin(config: &std::path::Path, args: &[&str]) {
45 );36 );
46 }37 }
47 38
48-/// The session's CSRF token, read from a page every signed-in user can open.
49 async fn csrf_for(http: &Http, session: &str) -> String {39 async fn csrf_for(http: &Http, session: &str) -> String {
50 let page = http.get("/settings/keys", Some(session)).await;40 let page = http.get("/settings/keys", Some(session)).await;
51 assert_eq!(page.status, 200, "GET /settings/keys");41 assert_eq!(page.status, 200, "GET /settings/keys");
52 input_value(&page.body, "csrf")42 input_value(&page.body, "csrf")
53 }43 }
54 44
55-/// Posts the transfer form on the settings page as `session`. Returns the response.
56 async fn offer(http: &Http, session: &str, owner: &str, repo: &str, to: &str) -> Resp {45 async fn offer(http: &Http, session: &str, owner: &str, repo: &str, to: &str) -> Resp {
57 let csrf = csrf_for(http, session).await;46 let csrf = csrf_for(http, session).await;
58 http.post_form(47 http.post_form(
@@ -67,7 +56,6 @@ async fn offer(http: &Http, session: &str, owner: &str, repo: &str, to: &str) ->
67 .await56 .await
68 }57 }
69 58
70-/// POSTs one of the transfer actions named by `suffix` from `page`, as `session`.
71 async fn act_from(http: &Http, session: &str, page: &str, suffix: &str) -> Resp {59 async fn act_from(http: &Http, session: &str, page: &str, suffix: &str) -> Resp {
72 let body = http.get(page, Some(session)).await.body;60 let body = http.get(page, Some(session)).await.body;
73 let action = form_action(&body, suffix);61 let action = form_action(&body, suffix);
@@ -83,7 +71,6 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
83 return;71 return;
84 }72 }
85 73
86- // Keep the path short: the data dir holds a unix socket with a length limit.
87 let root = tempfile::Builder::new()74 let root = tempfile::Builder::new()
88 .prefix("frt")75 .prefix("frt")
89 .tempdir_in("/tmp")76 .tempdir_in("/tmp")
@@ -92,8 +79,6 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
92 let ports = pick_ports();79 let ports = pick_ports();
93 let config = write_config(&dir, ports);80 let config = write_config(&dir, ports);
94 81
95- // Bob owns `priv` (private) and `pub`. Carol is an outsider who cannot read `priv`. Acme is an
96- // org owned by bob, with dave as a second owner and eve as a plain member.
97 admin(&config, &["create-user", "tahinli", "--admin"]);82 admin(&config, &["create-user", "tahinli", "--admin"]);
98 for name in ["bob", "carol", "dave", "eve"] {83 for name in ["bob", "carol", "dave", "eve"] {
99 admin(&config, &["create-user", name]);84 admin(&config, &["create-user", name]);
@@ -141,7 +126,6 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
141 let dave = login(&http, "dave", PW).await;126 let dave = login(&http, "dave", PW).await;
142 let eve = login(&http, "eve", PW).await;127 let eve = login(&http, "eve", PW).await;
143 128
144- // Offer, then decline as carol from the inbox. The repo stays with bob.
145 let offered = offer(&http, &bob, "bob", "priv", "carol").await;129 let offered = offer(&http, &bob, "bob", "priv", "carol").await;
146 assert_eq!(offered.status, 303, "offer: {}", offered.body);130 assert_eq!(offered.status, 303, "offer: {}", offered.body);
147 assert_eq!(131 assert_eq!(
@@ -152,7 +136,6 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
152 .get("/bob/priv/settings?section=danger", Some(&bob))136 .get("/bob/priv/settings?section=danger", Some(&bob))
153 .await;137 .await;
154 assert!(status.body.contains("Pending transfer to carol"));138 assert!(status.body.contains("Pending transfer to carol"));
155- // Carol cannot read the private repo, yet the inbox offers her the actions.
156 assert_eq!(http.get("/bob/priv", Some(&carol)).await.status, 404);139 assert_eq!(http.get("/bob/priv", Some(&carol)).await.status, 404);
157 let declined = act_from(&http, &carol, "/notifications", "/decline").await;140 let declined = act_from(&http, &carol, "/notifications", "/decline").await;
158 assert_eq!(declined.status, 303, "decline: {}", declined.body);141 assert_eq!(declined.status, 303, "decline: {}", declined.body);
@@ -163,7 +146,6 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
163 assert!(!after.body.contains("Pending transfer"));146 assert!(!after.body.contains("Pending transfer"));
164 assert_eq!(http.get("/bob/priv", Some(&bob)).await.status, 200);147 assert_eq!(http.get("/bob/priv", Some(&bob)).await.status, 200);
165 148
166- // Offer again, then the initiator cancels it.
167 assert_eq!(offer(&http, &bob, "bob", "priv", "carol").await.status, 303);149 assert_eq!(offer(&http, &bob, "bob", "priv", "carol").await.status, 303);
168 let cancelled = act_from(&http, &bob, "/bob/priv/settings?section=danger", "/cancel").await;150 let cancelled = act_from(&http, &bob, "/bob/priv/settings?section=danger", "/cancel").await;
169 assert_eq!(cancelled.status, 303, "cancel: {}", cancelled.body);151 assert_eq!(cancelled.status, 303, "cancel: {}", cancelled.body);
@@ -176,7 +158,6 @@ async fn repo_transfer_offers_declines_cancels_and_org_targets() {
176 .await;158 .await;
177 assert!(!after.body.contains("Pending transfer"));159 assert!(!after.body.contains("Pending transfer"));
178 160
179- // A transfer to an org: plain members get no accept form, owners do.
180 let to_org = offer(&http, &bob, "bob", "pub", "acme").await;161 let to_org = offer(&http, &bob, "bob", "pub", "acme").await;
181 assert_eq!(to_org.status, 303, "offer to org: {}", to_org.body);162 assert_eq!(to_org.status, 303, "offer to org: {}", to_org.body);
182 let eve_inbox = http.get("/notifications", Some(&eve)).await;163 let eve_inbox = http.get("/notifications", Some(&eve)).await;
crates/forge-e2e/tests/e2e/runner_subcommand.rsmodified+0 -11
@@ -1,7 +1,3 @@
1-//! `forge runner` is the forge CI runner, the same command line as `forge-runner`. These
2-//! tests check that the subcommand exists and that the sandbox helper, which the runner starts as
3-//! `<this executable> __sandbox`, is dispatched by this binary.
4-
5 use std::fs;1 use std::fs;
6 use std::path::Path;2 use std::path::Path;
7 use std::process::Command;3 use std::process::Command;
@@ -14,7 +10,6 @@ fn forge() -> Command {
14 Command::new(bin())10 Command::new(bin())
15 }11 }
16 12
17-/// Unprivileged user namespaces, as `crates/forge-runner/tests/sandbox.rs` checks them.
18 fn userns_available() -> bool {13 fn userns_available() -> bool {
19 let max = fs::read_to_string("/proc/sys/user/max_user_namespaces")14 let max = fs::read_to_string("/proc/sys/user/max_user_namespaces")
20 .ok()15 .ok()
@@ -29,8 +24,6 @@ fn userns_available() -> bool {
29 .is_ok_and(|s| s.success())24 .is_ok_and(|s| s.success())
30 }25 }
31 26
32-/// Gives every directory under `dir` owner access. Overlay work dirs are left without
33-/// permissions, and `TempDir` cannot remove them otherwise. Same approach as the executor.
34 fn make_removable(dir: &Path) {27 fn make_removable(dir: &Path) {
35 let _ = fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700));28 let _ = fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700));
36 let Ok(entries) = fs::read_dir(dir) else {29 let Ok(entries) = fs::read_dir(dir) else {
@@ -43,8 +36,6 @@ fn make_removable(dir: &Path) {
43 }36 }
44 }37 }
45 38
46-/// A work dir under the cargo target dir, removed on drop even when a job left overlay dirs
47-/// behind.
48 struct WorkDir(TempDir);39 struct WorkDir(TempDir);
49 40
50 impl WorkDir {41 impl WorkDir {
@@ -94,8 +85,6 @@ fn sandbox_helper_runs_through_forge() {
94 return;85 return;
95 }86 }
96 let work = WorkDir::new();87 let work = WorkDir::new();
97- // `runner check` runs one trivial job through the real sandbox. It is started as
98- // `forge __sandbox`, so a successful exit proves that dispatch works in this binary.
99 let out = forge()88 let out = forge()
100 .args(["runner", "check", "--work-dir"])89 .args(["runner", "check", "--work-dir"])
101 .arg(work.0.path())90 .arg(work.0.path())
crates/forge-e2e/tests/e2e/snippets_e2e.rsmodified+0 -18
@@ -1,7 +1,3 @@
1-//! Black-box tests for snippets. Like the other e2e tests, this starts the real `forge` binary and
2-//! drives it over HTTP. Cookies are set by hand because the session cookie is `__Host-` and
3-//! `Secure`. Files are fetched from the user-content listener, as a browser would.
4-
5 use crate::common::{1 use crate::common::{
6 Http, Server, bin, describe, input_value, launch, login, next_changed, pick_ports, write_config,2 Http, Server, bin, describe, input_value, launch, login, next_changed, pick_ports, write_config,
7 };3 };
@@ -12,7 +8,6 @@ use reqwest::header::{CONTENT_TYPE, LOCATION};
12 8
13 const PW: &str = "tahinli-password-123";9 const PW: &str = "tahinli-password-123";
14 10
15-/// The path and query of an absolute URL, so it can be requested through a base-bound client.
16 fn path_of(url: &str) -> String {11 fn path_of(url: &str) -> String {
17 let rest = url.split_once("//").map_or(url, |(_, r)| r);12 let rest = url.split_once("//").map_or(url, |(_, r)| r);
18 match rest.find('/') {13 match rest.find('/') {
@@ -21,7 +16,6 @@ fn path_of(url: &str) -> String {
21 }16 }
22 }17 }
23 18
24-/// The href of the first link whose text is `text`.
25 fn link_href(body: &str, text: &str) -> String {19 fn link_href(body: &str, text: &str) -> String {
26 let doc = scraper::Html::parse_document(body);20 let doc = scraper::Html::parse_document(body);
27 let selector = scraper::Selector::parse("a").expect("selector");21 let selector = scraper::Selector::parse("a").expect("selector");
@@ -32,7 +26,6 @@ fn link_href(body: &str, text: &str) -> String {
32 .to_owned()26 .to_owned()
33 }27 }
34 28
35-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
36 fn admin(config: &Path, args: &[&str]) {29 fn admin(config: &Path, args: &[&str]) {
37 let out = Command::new(bin())30 let out = Command::new(bin())
38 .arg("--config")31 .arg("--config")
@@ -49,7 +42,6 @@ fn admin(config: &Path, args: &[&str]) {
49 );42 );
50 }43 }
51 44
52-/// A running server. The temp dir lives as long as the test.
53 struct Env {45 struct Env {
54 _root: tempfile::TempDir,46 _root: tempfile::TempDir,
55 _server: Server,47 _server: Server,
@@ -73,7 +65,6 @@ async fn start() -> Env {
73 }65 }
74 }66 }
75 67
76-/// Creates a snippet as `cookie`'s user and returns its id.
77 async fn create(68 async fn create(
78 http: &Http,69 http: &Http,
79 cookie: &str,70 cookie: &str,
@@ -106,8 +97,6 @@ async fn create(
106 .to_owned()97 .to_owned()
107 }98 }
108 99
109-/// The list and the snippet page follow their streams. A create, an edit and a delete each wake
110-/// them, and a private snippet's stream answers 404 to everyone but its owner.
111 #[tokio::test]100 #[tokio::test]
112 async fn snippet_streams_follow_writes() {101 async fn snippet_streams_follow_writes() {
113 let env = start().await;102 let env = start().await;
@@ -124,7 +113,6 @@ async fn snippet_streams_follow_writes() {
124 .await;113 .await;
125 let item = format!("/snippets/{id}/events");114 let item = format!("/snippets/{id}/events");
126 115
127- // The pages render the streams they follow.
128 let listing = env.app.get("/snippets", Some(&tahinli)).await;116 let listing = env.app.get("/snippets", Some(&tahinli)).await;
129 assert!(117 assert!(
130 listing.body.contains(r#"data-live="/snippets/events""#),118 listing.body.contains(r#"data-live="/snippets/events""#),
@@ -144,7 +132,6 @@ async fn snippet_streams_follow_writes() {
144 let mut item_events = env.app.stream(&item, Some(&tahinli)).await;132 let mut item_events = env.app.stream(&item, Some(&tahinli)).await;
145 assert_eq!(item_events.status().as_u16(), 200, "snippet stream");133 assert_eq!(item_events.status().as_u16(), 200, "snippet stream");
146 134
147- // An edit wakes both.
148 let edit_path = format!("/snippets/{id}/edit");135 let edit_path = format!("/snippets/{id}/edit");
149 let csrf = input_value(&env.app.get(&edit_path, Some(&tahinli)).await.body, "csrf");136 let csrf = input_value(&env.app.get(&edit_path, Some(&tahinli)).await.body, "csrf");
150 let saved = env137 let saved = env
@@ -166,7 +153,6 @@ async fn snippet_streams_follow_writes() {
166 next_changed(&mut list_events, "an edit").await;153 next_changed(&mut list_events, "an edit").await;
167 next_changed(&mut item_events, "an edit").await;154 next_changed(&mut item_events, "an edit").await;
168 155
169- // A create wakes the list only.
170 let other = create(156 let other = create(
171 &env.app,157 &env.app,
172 &tahinli,158 &tahinli,
@@ -177,7 +163,6 @@ async fn snippet_streams_follow_writes() {
177 .await;163 .await;
178 next_changed(&mut list_events, "a create").await;164 next_changed(&mut list_events, "a create").await;
179 165
180- // A delete wakes the list, and the snippet's stream sends `changed` too: its page now 404s.
181 let csrf = input_value(166 let csrf = input_value(
182 &env.app167 &env.app
183 .get(&format!("/snippets/{other}"), Some(&tahinli))168 .get(&format!("/snippets/{other}"), Some(&tahinli))
@@ -196,7 +181,6 @@ async fn snippet_streams_follow_writes() {
196 assert_eq!(deleted.status, 303, "delete: {}", deleted.body);181 assert_eq!(deleted.status, 303, "delete: {}", deleted.body);
197 next_changed(&mut list_events, "a delete").await;182 next_changed(&mut list_events, "a delete").await;
198 183
199- // A private snippet: the owner's stream opens, everyone else gets 404 (anonymous too).
200 let secret = create(184 let secret = create(
201 &env.app,185 &env.app,
202 &tahinli,186 &tahinli,
@@ -328,7 +312,6 @@ async fn private_snippet_is_hidden_from_others() {
328 "private snippet is not listed for bob"312 "private snippet is not listed for bob"
329 );313 );
330 314
331- // Bob cannot edit or delete it either.
332 let page = env315 let page = env
333 .app316 .app
334 .get(&format!("/snippets/{id}/edit"), Some(&bob))317 .get(&format!("/snippets/{id}/edit"), Some(&bob))
@@ -387,7 +370,6 @@ async fn raw_files_use_the_user_content_origin_and_private_tokens() {
387 );370 );
388 assert_eq!(res.body, "# Hi\n");371 assert_eq!(res.body, "# Hi\n");
389 372
390- // Private raw links carry a signed token, and the bare path is refused.
391 let page = env373 let page = env
392 .app374 .app
393 .get(&format!("/snippets/{private}"), Some(&tahinli))375 .get(&format!("/snippets/{private}"), Some(&tahinli))
crates/forge-e2e/tests/e2e/stars_e2e.rsmodified+0 -17
@@ -1,7 +1,3 @@
1-//! Black-box tests for stars, the explore page, the starred profile section and the archived
2-//! banner. Like the other e2e tests, this starts the real `forge` binary and drives it over
3-//! HTTP. Cookies are set by hand because the session cookie is `__Host-` and `Secure`.
4-
5 use crate::common::{1 use crate::common::{
6 Http, PW, Resp, Server, admin, describe, init_bare, input_value, launch, login, pick_ports,2 Http, PW, Resp, Server, admin, describe, init_bare, input_value, launch, login, pick_ports,
7 tool_on_path, write_config,3 tool_on_path, write_config,
@@ -12,15 +8,12 @@ use std::process::{Command, Stdio};
12 use forge_core::{Store, Visibility};8 use forge_core::{Store, Visibility};
13 use reqwest::header::LOCATION;9 use reqwest::header::LOCATION;
14 10
15-/// A running server plus the data it was seeded with. The temp dir lives as long as the test.
16 struct Env {11 struct Env {
17 _root: tempfile::TempDir,12 _root: tempfile::TempDir,
18 _server: Server,13 _server: Server,
19 http: Http,14 http: Http,
20 }15 }
21 16
22-/// Creates the users and config, then runs `seed` against the store before the server starts.
23-/// The seed closure receives the data dir (for bare repos) and the open store.
24 async fn start<F, Fut>(seed: F) -> Env17 async fn start<F, Fut>(seed: F) -> Env
25 where18 where
26 F: FnOnce(PathBuf, Store) -> Fut,19 F: FnOnce(PathBuf, Store) -> Fut,
@@ -48,7 +41,6 @@ where
48 }41 }
49 }42 }
50 43
51-/// Tahinli owns `pub` (public), `priv` (private) and `pct%x` (public, for literal-search checks).
52 async fn seed_repos(dir: PathBuf, store: Store) {44 async fn seed_repos(dir: PathBuf, store: Store) {
53 let tahinli = store45 let tahinli = store
54 .user_by_username("tahinli")46 .user_by_username("tahinli")
@@ -68,7 +60,6 @@ async fn seed_repos(dir: PathBuf, store: Store) {
68 }60 }
69 }61 }
70 62
71-/// Writes one commit with a README to the bare repo's `main`, using plumbing only (no hooks).
72 fn commit_main(data_dir: &Path, repo_id: &str) {63 fn commit_main(data_dir: &Path, repo_id: &str) {
73 let id = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");64 let id = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
74 let blob = plumbing(&id, &["hash-object", "-w", "--stdin"], b"hello\n");65 let blob = plumbing(&id, &["hash-object", "-w", "--stdin"], b"hello\n");
@@ -81,7 +72,6 @@ fn commit_main(data_dir: &Path, repo_id: &str) {
81 let _ = plumbing(&id, &["update-ref", "refs/heads/main", &commit], b"");72 let _ = plumbing(&id, &["update-ref", "refs/heads/main", &commit], b"");
82 }73 }
83 74
84-/// Runs git against the bare repo at `path` with fixed identities and returns trimmed stdout.
85 fn plumbing(path: &Path, args: &[&str], stdin: &[u8]) -> String {75 fn plumbing(path: &Path, args: &[&str], stdin: &[u8]) -> String {
86 use std::io::Write;76 use std::io::Write;
87 let mut child = Command::new("git")77 let mut child = Command::new("git")
@@ -108,7 +98,6 @@ fn plumbing(path: &Path, args: &[&str], stdin: &[u8]) -> String {
108 String::from_utf8_lossy(&out.stdout).trim().to_owned()98 String::from_utf8_lossy(&out.stdout).trim().to_owned()
109 }99 }
110 100
111-/// Text of every `.repo-name` link on a page, in document order.
112 fn repo_names(body: &str) -> Vec<String> {101 fn repo_names(body: &str) -> Vec<String> {
113 let doc = scraper::Html::parse_document(body);102 let doc = scraper::Html::parse_document(body);
114 let selector = scraper::Selector::parse(".repo-name").expect("selector");103 let selector = scraper::Selector::parse(".repo-name").expect("selector");
@@ -117,7 +106,6 @@ fn repo_names(body: &str) -> Vec<String> {
117 .collect()106 .collect()
118 }107 }
119 108
120-/// Sends a star POST with an optional Referer header.
121 async fn post_star(109 async fn post_star(
122 http: &Http,110 http: &Http,
123 path: &str,111 path: &str,
@@ -159,7 +147,6 @@ async fn star_round_trip_shows_the_count() {
159 let page = env.http.get("/tahinli/pub", Some(&bob)).await;147 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
160 assert!(page.body.contains("Unstar 1"), "after star: {}", page.body);148 assert!(page.body.contains("Unstar 1"), "after star: {}", page.body);
161 149
162- // Back to the tree page through the Referer, when it is a same-origin path.
163 let referer = format!("{}/tahinli/pub/tree/main", env.http.base);150 let referer = format!("{}/tahinli/pub/tree/main", env.http.base);
164 let res = post_star(151 let res = post_star(
165 &env.http,152 &env.http,
@@ -177,7 +164,6 @@ async fn star_round_trip_shows_the_count() {
177 let page = env.http.get("/tahinli/pub", Some(&bob)).await;164 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
178 assert!(page.body.contains("Star 0"), "after unstar: {}", page.body);165 assert!(page.body.contains("Star 0"), "after unstar: {}", page.body);
179 166
180- // A Referer on another host is ignored.
181 let foreign = "https://evil.example/tahinli/pub";167 let foreign = "https://evil.example/tahinli/pub";
182 let res = post_star(168 let res = post_star(
183 &env.http,169 &env.http,
@@ -241,11 +227,9 @@ async fn explore_lists_public_repos_and_searches_literally() {
241 "private hidden: {names:?}"227 "private hidden: {names:?}"
242 );228 );
243 229
244- // `%` in the search is a literal percent sign, so only `pct%x` matches.
245 let page = env.http.get("/explore?q=%25", None).await;230 let page = env.http.get("/explore?q=%25", None).await;
246 assert_eq!(repo_names(&page.body), vec!["tahinli/pct%x".to_owned()]);231 assert_eq!(repo_names(&page.body), vec!["tahinli/pct%x".to_owned()]);
247 232
248- // Sorting by stars puts a starred repo first; the default (name) puts `pct%x` first.
249 let bob = login(&env.http, "bob", PW).await;233 let bob = login(&env.http, "bob", PW).await;
250 let page = env.http.get("/tahinli/pub", Some(&bob)).await;234 let page = env.http.get("/tahinli/pub", Some(&bob)).await;
251 let csrf = input_value(&page.body, "csrf");235 let csrf = input_value(&page.body, "csrf");
@@ -275,7 +259,6 @@ async fn profile_stars_tab_hides_repos_the_viewer_cannot_read() {
275 let bob = store.user_by_username("bob").await.unwrap().expect("bob");259 let bob = store.user_by_username("bob").await.unwrap().expect("bob");
276 let repos = store.list_repos_by_owner(&tahinli.id).await.unwrap();260 let repos = store.list_repos_by_owner(&tahinli.id).await.unwrap();
277 let find = |name: &str| repos.iter().find(|r| r.name == name).unwrap().id.clone();261 let find = |name: &str| repos.iter().find(|r| r.name == name).unwrap().id.clone();
278- // Bob stars a public repo and a private one he cannot read.
279 store.star(&bob.id, &find("pub")).await.unwrap();262 store.star(&bob.id, &find("pub")).await.unwrap();
280 store.star(&bob.id, &find("priv")).await.unwrap();263 store.star(&bob.id, &find("priv")).await.unwrap();
281 })264 })
crates/forge-e2e/tests/e2e/ui_prefs_e2e.rsmodified+0 -24
@@ -1,8 +1,3 @@
1-//! Black-box tests for the theme and language preferences: the appearance settings page, the
2-//! `data-theme` attribute on `<html>`, and the anonymous footer cookie. Like the other e2e
3-//! tests, this starts the real `forge` binary and drives it over HTTP. Cookies are set by hand
4-//! because the session cookie is `__Host-` and `Secure`.
5-
6 use crate::common::{1 use crate::common::{
7 Http, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports, write_config,2 Http, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports, write_config,
8 };3 };
@@ -11,20 +6,16 @@ use std::process::Command;
11 6
12 const PW: &str = "tahinli-password-123";7 const PW: &str = "tahinli-password-123";
13 8
14-/// The `data-theme` attribute of `<html>`, if the page sets one.
15 fn html_theme(body: &str) -> Option<String> {9 fn html_theme(body: &str) -> Option<String> {
16 let doc = scraper::Html::parse_document(body);10 let doc = scraper::Html::parse_document(body);
17 doc.root_element().attr("data-theme").map(str::to_owned)11 doc.root_element().attr("data-theme").map(str::to_owned)
18 }12 }
19 13
20-/// The value of attribute `name` on `<html>`, if the page sets it.
21 fn html_attr(body: &str, name: &str) -> Option<String> {14 fn html_attr(body: &str, name: &str) -> Option<String> {
22 let doc = scraper::Html::parse_document(body);15 let doc = scraper::Html::parse_document(body);
23 doc.root_element().attr(name).map(str::to_owned)16 doc.root_element().attr(name).map(str::to_owned)
24 }17 }
25 18
26-/// The four colour attributes of `<html>`, in the order light accent, dark accent, light base,
27-/// dark base.
28 fn html_colours(body: &str) -> [Option<String>; 4] {19 fn html_colours(body: &str) -> [Option<String>; 4] {
29 [20 [
30 html_attr(body, "data-accent-light"),21 html_attr(body, "data-accent-light"),
@@ -34,7 +25,6 @@ fn html_colours(body: &str) -> [Option<String>; 4] {
34 ]25 ]
35 }26 }
36 27
37-/// The checked radio of each colour group, in the same order as `html_colours`.
38 fn checked_colours(body: &str) -> [Option<String>; 4] {28 fn checked_colours(body: &str) -> [Option<String>; 4] {
39 [29 [
40 checked_radio(body, "accent_light"),30 checked_radio(body, "accent_light"),
@@ -44,7 +34,6 @@ fn checked_colours(body: &str) -> [Option<String>; 4] {
44 ]34 ]
45 }35 }
46 36
47-/// The value of the checked radio button in the group `name` on a page.
48 fn checked_radio(body: &str, name: &str) -> Option<String> {37 fn checked_radio(body: &str, name: &str) -> Option<String> {
49 let doc = scraper::Html::parse_document(body);38 let doc = scraper::Html::parse_document(body);
50 let selector =39 let selector =
@@ -56,7 +45,6 @@ fn checked_radio(body: &str, name: &str) -> Option<String> {
56 .map(str::to_owned)45 .map(str::to_owned)
57 }46 }
58 47
59-/// The option value that is selected in the `<select name="...">` on a page.
60 fn selected_option(body: &str, select: &str) -> Option<String> {48 fn selected_option(body: &str, select: &str) -> Option<String> {
61 let doc = scraper::Html::parse_document(body);49 let doc = scraper::Html::parse_document(body);
62 let selector = scraper::Selector::parse(&format!(50 let selector = scraper::Selector::parse(&format!(
@@ -69,7 +57,6 @@ fn selected_option(body: &str, select: &str) -> Option<String> {
69 .map(str::to_owned)57 .map(str::to_owned)
70 }58 }
71 59
72-/// The top-bar theme button: the value it posts and its accessible label.
73 fn theme_button(body: &str) -> (String, String) {60 fn theme_button(body: &str) -> (String, String) {
74 let doc = scraper::Html::parse_document(body);61 let doc = scraper::Html::parse_document(body);
75 let form = scraper::Selector::parse("form.theme-form").expect("selector");62 let form = scraper::Selector::parse("form.theme-form").expect("selector");
@@ -94,7 +81,6 @@ fn theme_button(body: &str) -> (String, String) {
94 (value, label)81 (value, label)
95 }82 }
96 83
97-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
98 fn admin(config: &Path, args: &[&str]) {84 fn admin(config: &Path, args: &[&str]) {
99 let out = Command::new(bin())85 let out = Command::new(bin())
100 .arg("--config")86 .arg("--config")
@@ -111,7 +97,6 @@ fn admin(config: &Path, args: &[&str]) {
111 );97 );
112 }98 }
113 99
114-/// A running server with user `tahinli`. The temp dir lives as long as the test.
115 struct Env {100 struct Env {
116 _root: tempfile::TempDir,101 _root: tempfile::TempDir,
117 _server: Server,102 _server: Server,
@@ -198,7 +183,6 @@ async fn the_form_has_no_save_button_and_every_field_autosubmits() {
198 scraper::Selector::parse("form[data-appearance] input, form[data-appearance] select")183 scraper::Selector::parse("form[data-appearance] input, form[data-appearance] select")
199 .expect("selector");184 .expect("selector");
200 for field in doc.select(&fields) {185 for field in doc.select(&fields) {
201- // The hidden fields never save, and the colour tab switch only shows a panel.
202 if field.value().attr("type") == Some("hidden")186 if field.value().attr("type") == Some("hidden")
203 || field.value().attr("data-colour-tab").is_some()187 || field.value().attr("data-colour-tab").is_some()
204 {188 {
@@ -246,7 +230,6 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() {
246 assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));230 assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));
247 assert_eq!(html_colours(&page.body), chosen.map(Some));231 assert_eq!(html_colours(&page.body), chosen.map(Some));
248 232
249- // A single field changes on its own; the other three keep their values.
250 let saved = env233 let saved = env
251 .http234 .http
252 .post_form(235 .post_form(
@@ -266,7 +249,6 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() {
266 assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));249 assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));
267 assert_eq!(html_colours(&page.body), chosen.map(Some));250 assert_eq!(html_colours(&page.body), chosen.map(Some));
268 251
269- // Malformed or unknown ids change nothing.
270 for (field, bad) in [252 for (field, bad) in [
271 ("accent_light", "Ocean"),253 ("accent_light", "Ocean"),
272 ("accent_dark", "../x"),254 ("accent_dark", "../x"),
@@ -292,7 +274,6 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() {
292 assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));274 assert_eq!(checked_colours(&page.body), chosen.clone().map(Some));
293 assert_eq!(html_colours(&page.body), chosen.map(Some));275 assert_eq!(html_colours(&page.body), chosen.map(Some));
294 276
295- // The newer accents and backgrounds save and show on the page the same way.
296 let saved = env277 let saved = env
297 .http278 .http
298 .post_form(279 .post_form(
@@ -311,13 +292,11 @@ async fn light_and_dark_colours_save_independently_and_render_on_html() {
311 .await;292 .await;
312 assert_eq!(saved.status, 303, "save: {}", saved.body);293 assert_eq!(saved.status, 303, "save: {}", saved.body);
313 let page = env.http.get("/settings/appearance", Some(&session)).await;294 let page = env.http.get("/settings/appearance", Some(&session)).await;
314- // The Custom radio carries the hue at the default vividness; the stored id stays `hue-200`.
315 let checked = ["hue-200-v50", "rose", "heather", "dusk"].map(str::to_owned);295 let checked = ["hue-200-v50", "rose", "heather", "dusk"].map(str::to_owned);
316 assert_eq!(checked_colours(&page.body), checked.map(Some));296 assert_eq!(checked_colours(&page.body), checked.map(Some));
317 let chosen = ["hue-200", "rose", "heather", "dusk"].map(str::to_owned);297 let chosen = ["hue-200", "rose", "heather", "dusk"].map(str::to_owned);
318 assert_eq!(html_colours(&page.body), chosen.map(Some));298 assert_eq!(html_colours(&page.body), chosen.map(Some));
319 299
320- // The newest accents and backgrounds save and show the same way.
321 let saved = env300 let saved = env
322 .http301 .http
323 .post_form(302 .post_form(
@@ -630,7 +609,6 @@ async fn theme_button_cycles_light_dark_auto_light_for_signed_in_users() {
630 let session = login(&env.http, "tahinli", PW).await;609 let session = login(&env.http, "tahinli", PW).await;
631 let back = "/settings/appearance";610 let back = "/settings/appearance";
632 611
633- // A new user starts on light, the default.
634 let page = env.http.get(back, Some(&session)).await;612 let page = env.http.get(back, Some(&session)).await;
635 let csrf = input_value(&page.body, "csrf");613 let csrf = input_value(&page.body, "csrf");
636 assert_eq!(html_theme(&page.body).as_deref(), Some("light"));614 assert_eq!(html_theme(&page.body).as_deref(), Some("light"));
@@ -680,7 +658,6 @@ async fn theme_button_cycles_light_dark_auto_light_for_signed_in_users() {
680 #[tokio::test]658 #[tokio::test]
681 async fn theme_button_cycles_for_anonymous_visitors_through_the_cookie() {659 async fn theme_button_cycles_for_anonymous_visitors_through_the_cookie() {
682 let env = start().await;660 let env = start().await;
683- // No cookie is the default, light, so the button offers dark next.
684 let page = env.http.get("/login", None).await;661 let page = env.http.get("/login", None).await;
685 assert_eq!(662 assert_eq!(
686 theme_button(&page.body),663 theme_button(&page.body),
@@ -737,7 +714,6 @@ async fn appearance_sidebar_side_saves_and_renders_on_html() {
737 Some("right")714 Some("right")
738 );715 );
739 716
740- // A save without the field keeps the side; a malformed side changes nothing.
741 let saved = env717 let saved = env
742 .http718 .http
743 .post_form(719 .post_form(
crates/forge-e2e/tests/e2e/user_delete_e2e.rsmodified+0 -12
@@ -1,8 +1,3 @@
1-//! Black-box tests for account deletion: the admin delete page, the self-service section on
2-//! /settings/security, and what stays visible afterwards. Like the other e2e tests, this starts
3-//! the real `forge` binary and drives it over HTTP. Cookies are set by hand because the
4-//! session cookie is `__Host-` and `Secure`.
5-
6 use crate::common::{1 use crate::common::{
7 Http, Resp, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports,2 Http, Resp, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports,
8 write_config,3 write_config,
@@ -17,7 +12,6 @@ use reqwest::header::LOCATION;
17 12
18 const PW: &str = "tahinli-password-123";13 const PW: &str = "tahinli-password-123";
19 14
20-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
21 fn admin(config: &Path, args: &[&str]) {15 fn admin(config: &Path, args: &[&str]) {
22 let out = Command::new(bin())16 let out = Command::new(bin())
23 .arg("--config")17 .arg("--config")
@@ -34,7 +28,6 @@ fn admin(config: &Path, args: &[&str]) {
34 );28 );
35 }29 }
36 30
37-/// Submits the login form. Returns the response, so callers decide what it means.
38 async fn try_login(http: &Http, username: &str) -> Resp {31 async fn try_login(http: &Http, username: &str) -> Resp {
39 let page = http.get("/login", None).await;32 let page = http.get("/login", None).await;
40 assert_eq!(page.status, 200, "GET /login");33 assert_eq!(page.status, 200, "GET /login");
@@ -53,8 +46,6 @@ async fn try_login(http: &Http, username: &str) -> Resp {
53 .await46 .await
54 }47 }
55 48
56-/// Creates the users (`dana` is the first user, so an administrator), then runs `seed` against
57-/// the store before the server starts. `seed` gets the data dir and the open store.
58 struct Env {49 struct Env {
59 _root: tempfile::TempDir,50 _root: tempfile::TempDir,
60 dir: PathBuf,51 dir: PathBuf,
@@ -88,7 +79,6 @@ where
88 }79 }
89 }80 }
90 81
91-/// Bob owns public `proj`. Tahinli wrote issue #1 and a comment on it.
92 async fn seed_issue_by_tahinli(dir: PathBuf, store: Store) {82 async fn seed_issue_by_tahinli(dir: PathBuf, store: Store) {
93 let tahinli = store83 let tahinli = store
94 .user_by_username("tahinli")84 .user_by_username("tahinli")
@@ -171,7 +161,6 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() {
171 let env = start(seed_issue_by_tahinli).await;161 let env = start(seed_issue_by_tahinli).await;
172 let http = &env.http;162 let http = &env.http;
173 163
174- // Tahinli owns nothing: a wrong password is refused and the account stays.
175 let tahinli = login(http, "tahinli", PW).await;164 let tahinli = login(http, "tahinli", PW).await;
176 let security = http.get("/settings/security", Some(&tahinli)).await;165 let security = http.get("/settings/security", Some(&tahinli)).await;
177 assert_eq!(security.status, 200);166 assert_eq!(security.status, 200);
@@ -198,7 +187,6 @@ async fn self_delete_refuses_wrong_password_and_owned_repos() {
198 "account must still exist"187 "account must still exist"
199 );188 );
200 189
201- // Bob owns `proj`: deletion is refused and the repo is named.
202 let bob = login(http, "bob", PW).await;190 let bob = login(http, "bob", PW).await;
203 let security = http.get("/settings/security", Some(&bob)).await;191 let security = http.get("/settings/security", Some(&bob)).await;
204 let csrf = input_value(&security.body, "csrf");192 let csrf = input_value(&security.body, "csrf");
crates/forge-e2e/tests/e2e/wiki_e2e.rsmodified+0 -31
@@ -1,10 +1,3 @@
1-//! Black-box test for the repo wiki. It seeds users and a repo through the store, starts the real
2-//! `forge` binary and drives the wiki pages, the HTTPS clone and push of `<repo>.wiki.git`, the
3-//! read-only and stale-edit refusals, and the backup of the wiki.
4-//!
5-//! Cookies are handled by hand because the session cookie is `__Host-forge_session` with `Secure`,
6-//! which a cookie jar would not send over plain http.
7-
8 use crate::common::{1 use crate::common::{
9 Http, Resp, bin, describe, input_value, launch, login, pick_ports, write_config,2 Http, Resp, bin, describe, input_value, launch, login, pick_ports, write_config,
10 };3 };
@@ -18,7 +11,6 @@ use reqwest::header::{COOKIE, LOCATION};
18 11
19 const PW: &str = "tahinli-password-123";12 const PW: &str = "tahinli-password-123";
20 13
21-/// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
22 fn admin(config: &Path, args: &[&str]) {14 fn admin(config: &Path, args: &[&str]) {
23 let out = Command::new(bin())15 let out = Command::new(bin())
24 .arg("--config")16 .arg("--config")
@@ -35,14 +27,12 @@ fn admin(config: &Path, args: &[&str]) {
35 );27 );
36 }28 }
37 29
38-/// The session's CSRF token, read from a page every signed-in user can open.
39 async fn csrf_for(http: &Http, session: &str) -> String {30 async fn csrf_for(http: &Http, session: &str) -> String {
40 let page = http.get("/settings/keys", Some(session)).await;31 let page = http.get("/settings/keys", Some(session)).await;
41 assert_eq!(page.status, 200, "GET /settings/keys");32 assert_eq!(page.status, 200, "GET /settings/keys");
42 input_value(&page.body, "csrf")33 input_value(&page.body, "csrf")
43 }34 }
44 35
45-/// Creates an access token through `/settings/tokens` and returns the token shown once.
46 async fn create_token(http: &Http, session: &str, name: &str) -> String {36 async fn create_token(http: &Http, session: &str, name: &str) -> String {
47 let csrf = csrf_for(http, session).await;37 let csrf = csrf_for(http, session).await;
48 let res = http38 let res = http
@@ -66,7 +56,6 @@ async fn create_token(http: &Http, session: &str, name: &str) -> String {
66 token56 token
67 }57 }
68 58
69-/// Creates a bare git repo for `repo_id` at its data-dir location, as the create-repo page does.
70 fn init_bare(data_dir: &Path, repo_id: &str) {59 fn init_bare(data_dir: &Path, repo_id: &str) {
71 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");60 let path = forge_git::repo::repo_path(data_dir, repo_id).expect("repo path");
72 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");61 fs::create_dir_all(path.parent().expect("parent")).expect("create repo parent");
@@ -96,7 +85,6 @@ fn path_str(path: &Path) -> &str {
96 path.to_str().expect("utf-8 path")85 path.to_str().expect("utf-8 path")
97 }86 }
98 87
99-/// Writes a file under `repo` (creating its directory) and commits it as `bob`.
100 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {88 fn commit_file(repo: &Path, name: &str, content: &str, message: &str) {
101 let file = repo.join(name);89 let file = repo.join(name);
102 fs::create_dir_all(file.parent().expect("parent")).expect("create dir");90 fs::create_dir_all(file.parent().expect("parent")).expect("create dir");
@@ -124,7 +112,6 @@ async fn get_ok(http: &Http, path: &str, session: Option<&str>) -> Resp {
124 112
125 #[tokio::test]113 #[tokio::test]
126 async fn wiki_end_to_end() {114 async fn wiki_end_to_end() {
127- // Keep the path short: the data dir holds a unix socket with a length limit.
128 let root = tempfile::Builder::new()115 let root = tempfile::Builder::new()
129 .prefix("fwk")116 .prefix("fwk")
130 .tempdir_in("/tmp")117 .tempdir_in("/tmp")
@@ -133,7 +120,6 @@ async fn wiki_end_to_end() {
133 let ports = pick_ports();120 let ports = pick_ports();
134 let config = write_config(&dir, ports);121 let config = write_config(&dir, ports);
135 122
136- // Bob owns a public repo. Carol has Write on it. Dave has only the Read that a public repo gives.
137 admin(&config, &["create-user", "tahinli", "--admin"]);123 admin(&config, &["create-user", "tahinli", "--admin"]);
138 for name in ["bob", "carol", "dave"] {124 for name in ["bob", "carol", "dave"] {
139 admin(&config, &["create-user", name]);125 admin(&config, &["create-user", name]);
@@ -165,11 +151,9 @@ async fn wiki_end_to_end() {
165 let carol = login(&http, "carol", PW).await;151 let carol = login(&http, "carol", PW).await;
166 let dave = login(&http, "dave", PW).await;152 let dave = login(&http, "dave", PW).await;
167 153
168- // The wiki starts empty, and the tab is there.
169 let empty = get_ok(&http, "/bob/proj/wiki", Some(&bob)).await;154 let empty = get_ok(&http, "/bob/proj/wiki", Some(&bob)).await;
170 assert!(empty.body.contains("no pages yet"), "{}", empty.body);155 assert!(empty.body.contains("no pages yet"), "{}", empty.body);
171 156
172- // Bob creates Home on the web. The save redirects to the page.
173 let csrf = input_value(157 let csrf = input_value(
174 &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,158 &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,
175 "csrf",159 "csrf",
@@ -200,12 +184,10 @@ async fn wiki_end_to_end() {
200 home.body184 home.body
201 );185 );
202 186
203- // Dave can read the page but not edit it.
204 get_ok(&http, "/bob/proj/wiki/Home", Some(&dave)).await;187 get_ok(&http, "/bob/proj/wiki/Home", Some(&dave)).await;
205 let refused = http.get("/bob/proj/wiki/Home/edit", Some(&dave)).await;188 let refused = http.get("/bob/proj/wiki/Home/edit", Some(&dave)).await;
206 assert_eq!(refused.status, 403, "read-only user must not edit");189 assert_eq!(refused.status, 403, "read-only user must not edit");
207 190
208- // Carol clones the wiki over HTTPS, sees Home, and pushes a change.
209 let carol_token = create_token(&http, &carol, "wiki-e2e").await;191 let carol_token = create_token(&http, &carol, "wiki-e2e").await;
210 let work = dir.join("wiki-work");192 let work = dir.join("wiki-work");
211 let url = format!(193 let url = format!(
@@ -229,7 +211,6 @@ async fn wiki_end_to_end() {
229 "{}",211 "{}",
230 after_push.body212 after_push.body
231 );213 );
232- // The push is in the admin audit log (read over HTTP, the server holds the database open).
233 let tahinli = login(&http, "tahinli", PW).await;214 let tahinli = login(&http, "tahinli", PW).await;
234 let audit = http215 let audit = http
235 .get("/admin/audit?action=wiki_pushed", Some(&tahinli))216 .get("/admin/audit?action=wiki_pushed", Some(&tahinli))
@@ -243,7 +224,6 @@ async fn wiki_end_to_end() {
243 assert!(audit.body.contains("carol"), "the pusher is named");224 assert!(audit.body.contains("carol"), "the pusher is named");
244 assert!(audit.body.contains("bob/proj"), "the repo is named");225 assert!(audit.body.contains("bob/proj"), "the repo is named");
245 226
246- // A save that started from the old head is refused with the conflict message, not applied.
247 let stale_csrf = input_value(227 let stale_csrf = input_value(
248 &http228 &http
249 .get("/bob/proj/wiki/Home/edit", Some(&carol))229 .get("/bob/proj/wiki/Home/edit", Some(&carol))
@@ -272,12 +252,10 @@ async fn wiki_end_to_end() {
272 let still = get_ok(&http, "/bob/proj/wiki/Home", Some(&bob)).await;252 let still = get_ok(&http, "/bob/proj/wiki/Home", Some(&bob)).await;
273 assert!(still.body.contains("Welcome again"), "{}", still.body);253 assert!(still.body.contains("Welcome again"), "{}", still.body);
274 254
275- // The history lists both edits.
276 let history = get_ok(&http, "/bob/proj/wiki/Home/history", Some(&bob)).await;255 let history = get_ok(&http, "/bob/proj/wiki/Home/history", Some(&bob)).await;
277 assert!(history.body.contains("first page"), "{}", history.body);256 assert!(history.body.contains("first page"), "{}", history.body);
278 assert!(history.body.contains("edit from git"), "{}", history.body);257 assert!(history.body.contains("edit from git"), "{}", history.body);
279 258
280- // Dave cannot push to the wiki.
281 let dave_token = create_token(&http, &dave, "wiki-e2e").await;259 let dave_token = create_token(&http, &dave, "wiki-e2e").await;
282 let dave_url = format!(260 let dave_url = format!(
283 "http://dave:{dave_token}@127.0.0.1:{}/bob/proj.wiki.git",261 "http://dave:{dave_token}@127.0.0.1:{}/bob/proj.wiki.git",
@@ -292,7 +270,6 @@ async fn wiki_end_to_end() {
292 let denied = git(&dave_work, &["push", "-q", "origin", "HEAD:main"]);270 let denied = git(&dave_work, &["push", "-q", "origin", "HEAD:main"]);
293 assert!(!denied.status.success(), "read-only push must fail");271 assert!(!denied.status.success(), "read-only push must fail");
294 272
295- // Bob turns the wiki off on the settings page. Carol, who is not an admin, cannot.
296 let settings = get_ok(&http, "/bob/proj/settings", Some(&bob)).await;273 let settings = get_ok(&http, "/bob/proj/settings", Some(&bob)).await;
297 assert!(274 assert!(
298 settings.body.contains("action=\"/bob/proj/settings/wiki\""),275 settings.body.contains("action=\"/bob/proj/settings/wiki\""),
@@ -324,7 +301,6 @@ async fn wiki_end_to_end() {
324 drop(server);301 drop(server);
325 }302 }
326 303
327-/// Opens a wiki stream as `cookie` (or anonymously) and reads its `retry` field.
328 async fn open_wiki_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {304 async fn open_wiki_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqwest::Response {
329 let mut req = http.client.get(format!("{}{path}", http.base));305 let mut req = http.client.get(format!("{}{path}", http.base));
330 if let Some(cookie) = cookie {306 if let Some(cookie) = cookie {
@@ -341,7 +317,6 @@ async fn open_wiki_stream(http: &Http, path: &str, cookie: Option<&str>) -> reqw
341 res317 res
342 }318 }
343 319
344-/// Waits for the next event of a wiki stream, which must be `changed`.
345 async fn next_wiki_change(res: &mut reqwest::Response, what: &str) {320 async fn next_wiki_change(res: &mut reqwest::Response, what: &str) {
346 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())321 let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
347 .await322 .await
@@ -352,8 +327,6 @@ async fn next_wiki_change(res: &mut reqwest::Response, what: &str) {
352 assert!(text.contains("event: changed"), "{what}: {text}");327 assert!(text.contains("event: changed"), "{what}: {text}");
353 }328 }
354 329
355-/// The wiki pages render their streams. A save from the web and a push from the wiki repo each
356-/// wake the wiki streams, and a viewer who cannot read the repo gets 404 from them.
357 #[tokio::test]330 #[tokio::test]
358 async fn wiki_streams_follow_saves_and_pushes() {331 async fn wiki_streams_follow_saves_and_pushes() {
359 let root = tempfile::Builder::new()332 let root = tempfile::Builder::new()
@@ -390,7 +363,6 @@ async fn wiki_streams_follow_saves_and_pushes() {
390 let bob = login(&http, "bob", PW).await;363 let bob = login(&http, "bob", PW).await;
391 let dave = login(&http, "dave", PW).await;364 let dave = login(&http, "dave", PW).await;
392 365
393- // The page list follows the wiki stream.
394 let listing = get_ok(&http, "/bob/proj/wiki/-/pages", Some(&bob)).await;366 let listing = get_ok(&http, "/bob/proj/wiki/-/pages", Some(&bob)).await;
395 assert!(367 assert!(
396 listing368 listing
@@ -399,7 +371,6 @@ async fn wiki_streams_follow_saves_and_pushes() {
399 "page list follows the wiki stream"371 "page list follows the wiki stream"
400 );372 );
401 373
402- // Bob opens the wiki stream, then creates Home on the web: the stream wakes.
403 let mut wiki_events = open_wiki_stream(&http, "/bob/proj/wiki/-/events", Some(&bob)).await;374 let mut wiki_events = open_wiki_stream(&http, "/bob/proj/wiki/-/events", Some(&bob)).await;
404 let csrf = input_value(375 let csrf = input_value(
405 &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,376 &http.get("/bob/proj/wiki/-/new", Some(&bob)).await.body,
@@ -421,7 +392,6 @@ async fn wiki_streams_follow_saves_and_pushes() {
421 assert_eq!(created.status, 303, "create Home: {}", created.body);392 assert_eq!(created.status, 303, "create Home: {}", created.body);
422 next_wiki_change(&mut wiki_events, "a web save").await;393 next_wiki_change(&mut wiki_events, "a web save").await;
423 394
424- // The page's own stream follows Home, and a push from git wakes it.
425 let home = get_ok(&http, "/bob/proj/wiki/Home", Some(&bob)).await;395 let home = get_ok(&http, "/bob/proj/wiki/Home", Some(&bob)).await;
426 assert!(396 assert!(
427 home.body397 home.body
@@ -446,7 +416,6 @@ async fn wiki_streams_follow_saves_and_pushes() {
446 );416 );
447 next_wiki_change(&mut home_events, "a push to the wiki").await;417 next_wiki_change(&mut home_events, "a push to the wiki").await;
448 418
449- // A viewer who cannot read the private repo gets 404 from its streams.
450 for path in ["/bob/vault/wiki/-/events", "/bob/vault/wiki/Home/events"] {419 for path in ["/bob/vault/wiki/-/events", "/bob/vault/wiki/Home/events"] {
451 let res = http.get(path, Some(&dave)).await;420 let res = http.get(path, Some(&dave)).await;
452 assert_eq!(res.status, 404, "{path} for a non-member");421 assert_eq!(res.status, 404, "{path} for a non-member");
crates/forge-git/src/backup.rsmodified+0 -26
@@ -1,6 +1,3 @@
1-//! Git side of backups: bundles of whole repos, bundle verification and the refs checksum.
2-//! Every git call goes through [`GitCommand`]. Paths are chosen by the server, never by a user.
3-
4 use std::path::Path;1 use std::path::Path;
5 2
6 use sha2::{Digest, Sha256};3 use sha2::{Digest, Sha256};
@@ -15,7 +12,6 @@ fn path_str(p: &Path) -> Result<&str> {
15 .ok_or_else(|| Error::InvalidInput(format!("path is not valid UTF-8: {}", p.display())))12 .ok_or_else(|| Error::InvalidInput(format!("path is not valid UTF-8: {}", p.display())))
16 }13 }
17 14
18-/// Output of `git for-each-ref --format='%(objectname) %(refname)'`, one line per ref.
19 async fn refs_listing(env: &GitEnv, repo: &Path) -> Result<Vec<u8>> {15 async fn refs_listing(env: &GitEnv, repo: &Path) -> Result<Vec<u8>> {
20 GitCommand::new(env, "for-each-ref")16 GitCommand::new(env, "for-each-ref")
21 .git_dir(repo)17 .git_dir(repo)
@@ -24,16 +20,11 @@ async fn refs_listing(env: &GitEnv, repo: &Path) -> Result<Vec<u8>> {
24 .await20 .await
25 }21 }
26 22
27-/// sha256 (lowercase hex) of the sorted `for-each-ref` lines, each followed by `\n`. An empty
28-/// repo gives the sha256 of the empty string. This is the reconcile checksum from architecture
29-/// §8.2, recorded in the backup manifest as `refs_sha256`.
30 pub async fn refs_checksum(env: &GitEnv, repo: &Path) -> Result<String> {23 pub async fn refs_checksum(env: &GitEnv, repo: &Path) -> Result<String> {
31 let out = refs_listing(env, repo).await?;24 let out = refs_listing(env, repo).await?;
32 Ok(refs_checksum_of_listing(&out))25 Ok(refs_checksum_of_listing(&out))
33 }26 }
34 27
35-/// The same checksum as [`refs_checksum`], computed from `for-each-ref --format='%(objectname)
36-/// %(refname)'` output that was obtained elsewhere (for example from a remote over ssh).
37 pub fn refs_checksum_of_listing(listing: &[u8]) -> String {28 pub fn refs_checksum_of_listing(listing: &[u8]) -> String {
38 let mut lines: Vec<&[u8]> = listing29 let mut lines: Vec<&[u8]> = listing
39 .split(|b| *b == b'\n')30 .split(|b| *b == b'\n')
@@ -48,10 +39,6 @@ pub fn refs_checksum_of_listing(listing: &[u8]) -> String {
48 hex::encode(hasher.finalize())39 hex::encode(hasher.finalize())
49 }40 }
50 41
51-/// Writes `git bundle create <out> --all` for `repo`. `out` must not exist. Returns `Ok(false)`
52-/// without writing anything when the repo has no refs, because git refuses to create an empty
53-/// bundle. Returns `Ok(true)` when the bundle was written. The caller must `bundle_verify` it.
54-/// The written file is set to mode 0600.
55 pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<bool> {42 pub async fn bundle_create(env: &GitEnv, repo: &Path, out: &Path) -> Result<bool> {
56 if std::fs::symlink_metadata(out).is_ok() {43 if std::fs::symlink_metadata(out).is_ok() {
57 return Err(Error::InvalidInput(format!(44 return Err(Error::InvalidInput(format!(
@@ -83,18 +70,6 @@ fn set_private_mode(path: &Path) -> Result<()> {
83 Ok(())70 Ok(())
84 }71 }
85 72
86-/// Verifies a bundle by really importing it, and returns the [`refs_checksum`] of what was
87-/// imported. `scratch_repo` must be a fresh, empty bare repo that the caller created for this one
88-/// bundle. The steps are:
89-///
90-/// 1. `git bundle verify`, which checks the header and prerequisites only. It does not notice a
91-/// truncated pack, so it is not enough on its own.
92-/// 2. `git fetch <bundle> +refs/*:refs/*` into the scratch repo, which reads and indexes the
93-/// whole pack.
94-/// 3. `git fsck --full` on the scratch repo, which checks every object it now holds.
95-///
96-/// Any failure is an error. The returned checksum must equal the `refs_sha256` recorded when the
97-/// bundle was made.
98 pub async fn bundle_verify(env: &GitEnv, scratch_repo: &Path, bundle: &Path) -> Result<String> {73 pub async fn bundle_verify(env: &GitEnv, scratch_repo: &Path, bundle: &Path) -> Result<String> {
99 let bundle_str = path_str(bundle)?;74 let bundle_str = path_str(bundle)?;
100 GitCommand::new(env, "bundle")75 GitCommand::new(env, "bundle")
@@ -143,7 +118,6 @@ mod tests {
143 assert!(out.status.success(), "git {args:?}: {out:?}");118 assert!(out.status.success(), "git {args:?}: {out:?}");
144 }119 }
145 120
146- /// A work repo with one commit, a branch and a tag. Returns its `.git` dir.
147 fn repo_with_refs(dir: &Path) -> std::path::PathBuf {121 fn repo_with_refs(dir: &Path) -> std::path::PathBuf {
148 let work = dir.join("work");122 let work = dir.join("work");
149 std::fs::create_dir_all(&work).expect("mkdir");123 std::fs::create_dir_all(&work).expect("mkdir");
crates/forge-git/src/blame.rsmodified+0 -14
@@ -1,6 +1,3 @@
1-//! `blame --porcelain`, parsed into runs of consecutive lines that share a commit.
2-//! The subprocess pattern is the same as `history`: validated arguments, a byte cap on stdout.
3-
4 use std::collections::HashMap;1 use std::collections::HashMap;
5 use std::path::Path;2 use std::path::Path;
6 3
@@ -9,23 +6,18 @@ use crate::command::GitEnv;
9 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
10 use crate::history::{git, read_capped, validate_oid};7 use crate::history::{git, read_capped, validate_oid};
11 8
12-/// What blame knows about one commit.
13 #[derive(Debug, Clone, PartialEq, Eq)]9 #[derive(Debug, Clone, PartialEq, Eq)]
14 pub struct BlameCommit {10 pub struct BlameCommit {
15 pub oid: String,11 pub oid: String,
16 pub author: String,12 pub author: String,
17 pub author_time: i64,13 pub author_time: i64,
18 pub summary: String,14 pub summary: String,
19- /// The parent revision and the file's name there, for "blame prior to this commit". None for
20- /// a boundary or root commit.
21 pub previous: Option<(String, String)>,15 pub previous: Option<(String, String)>,
22 }16 }
23 17
24-/// A run of consecutive final lines that came from the same commit.
25 #[derive(Debug, Clone, PartialEq, Eq)]18 #[derive(Debug, Clone, PartialEq, Eq)]
26 pub struct BlameGroup {19 pub struct BlameGroup {
27 pub commit: String,20 pub commit: String,
28- /// First final line number of the run (1-based).
29 pub start: u32,21 pub start: u32,
30 pub lines: u32,22 pub lines: u32,
31 }23 }
@@ -34,7 +26,6 @@ pub struct BlameGroup {
34 pub struct Blame {26 pub struct Blame {
35 pub groups: Vec<BlameGroup>,27 pub groups: Vec<BlameGroup>,
36 pub commits: HashMap<String, BlameCommit>,28 pub commits: HashMap<String, BlameCommit>,
37- /// Total lines blamed.
38 pub total: u32,29 pub total: u32,
39 }30 }
40 31
@@ -47,7 +38,6 @@ fn is_header(line: &str) -> Option<(&str, u32)> {
47 Some((oid, fin))38 Some((oid, fin))
48 }39 }
49 40
50-/// Parses `--porcelain` output.
51 pub fn parse_porcelain(text: &str) -> Blame {41 pub fn parse_porcelain(text: &str) -> Blame {
52 let mut commits: HashMap<String, BlameCommit> = HashMap::new();42 let mut commits: HashMap<String, BlameCommit> = HashMap::new();
53 let mut groups: Vec<BlameGroup> = Vec::new();43 let mut groups: Vec<BlameGroup> = Vec::new();
@@ -55,7 +45,6 @@ pub fn parse_porcelain(text: &str) -> Blame {
55 let mut total = 0u32;45 let mut total = 0u32;
56 for line in text.split('\n') {46 for line in text.split('\n') {
57 if line.starts_with('\t') {47 if line.starts_with('\t') {
58- // Content line: the final line number came from the header just before it.
59 continue;48 continue;
60 }49 }
61 if let Some((oid, fin)) = is_header(line) {50 if let Some((oid, fin)) = is_header(line) {
@@ -105,8 +94,6 @@ pub fn parse_porcelain(text: &str) -> Blame {
105 }94 }
106 }95 }
107 96
108-/// Blames `path` at `commit` (a full oid). Output beyond the cap is an error, so the caller can
109-/// show its "too large" message rather than a partial blame. The caller bounds the run time.
110 pub async fn blame(97 pub async fn blame(
111 env: &GitEnv,98 env: &GitEnv,
112 repo: &Path,99 repo: &Path,
@@ -118,7 +105,6 @@ pub async fn blame(
118 validate_repo_path(path)?;105 validate_repo_path(path)?;
119 let cmd = git(env, "blame").git_dir(repo).arg("--porcelain");106 let cmd = git(env, "blame").git_dir(repo).arg("--porcelain");
120 let cmd = if ignore_ws { cmd.arg("-w") } else { cmd };107 let cmd = if ignore_ws { cmd.arg("-w") } else { cmd };
121- // `blame` does not understand `--end-of-options`; the oid is validated hex.
122 let cmd = cmd.user_arg(commit)?.paths(&[path]);108 let cmd = cmd.user_arg(commit)?.paths(&[path]);
123 let (buf, complete) = read_capped(cmd).await?;109 let (buf, complete) = read_capped(cmd).await?;
124 if !complete {110 if !complete {
crates/forge-git/src/branches.rsmodified+0 -5
@@ -1,5 +1,3 @@
1-//! Branch operations used by the branches page: ahead/behind counts, creating and deleting.
2-
3 use std::path::Path;1 use std::path::Path;
4 2
5 use crate::command::GitEnv;3 use crate::command::GitEnv;
@@ -7,7 +5,6 @@ use crate::error::{Error, Result};
7 use crate::history::{git, validate_oid, zero_oid};5 use crate::history::{git, validate_oid, zero_oid};
8 use crate::pulls::{delete_ref_cas, update_ref_cas};6 use crate::pulls::{delete_ref_cas, update_ref_cas};
9 7
10-/// `(ahead, behind)` of `tip` relative to `base`: commits only in `tip`, and commits only in `base`.
11 pub async fn ahead_behind(env: &GitEnv, repo: &Path, base: &str, tip: &str) -> Result<(u32, u32)> {8 pub async fn ahead_behind(env: &GitEnv, repo: &Path, base: &str, tip: &str) -> Result<(u32, u32)> {
12 validate_oid(base)?;9 validate_oid(base)?;
13 validate_oid(tip)?;10 validate_oid(tip)?;
@@ -31,7 +28,6 @@ pub async fn ahead_behind(env: &GitEnv, repo: &Path, base: &str, tip: &str) -> R
31 }28 }
32 }29 }
33 30
34-/// Creates `refs/heads/<name>` at `oid`. Fails when the branch exists already.
35 pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {31 pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {
36 validate_oid(oid)?;32 validate_oid(oid)?;
37 update_ref_cas(33 update_ref_cas(
@@ -44,7 +40,6 @@ pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) ->
44 .await40 .await
45 }41 }
46 42
47-/// Deletes `refs/heads/<name>` if it still points at `oid`.
48 pub async fn delete_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {43 pub async fn delete_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {
49 delete_ref_cas(env, repo, &format!("refs/heads/{name}"), oid).await44 delete_ref_cas(env, repo, &format!("refs/heads/{name}"), oid).await
50 }45 }
crates/forge-git/src/browse.rsmodified+3 -48
@@ -1,8 +1,3 @@
1-//! In-process repo reads via gix.
2-//!
3-//! Everything here is blocking; callers run it inside `spawn_blocking`. Repositories are opened
4-//! isolated: the environment and user/system git configuration are ignored.
5-
6 use std::collections::HashSet;1 use std::collections::HashSet;
7 use std::path::Path;2 use std::path::Path;
8 3
@@ -11,9 +6,7 @@ use gix::objs::tree::EntryKind as GixEntryKind;
11 6
12 use crate::error::{Error, Result};7 use crate::error::{Error, Result};
13 8
14-/// Bytes inspected for a NUL when deciding whether a blob is binary.
15 const BINARY_PROBE_BYTES: usize = 8000;9 const BINARY_PROBE_BYTES: usize = 8000;
16-/// Maximum accepted length of a repo path, in bytes.
17 const MAX_PATH_BYTES: usize = 4096;10 const MAX_PATH_BYTES: usize = 4096;
18 11
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]12 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -26,9 +19,9 @@ pub enum RefKind {
26 pub struct RefInfo {19 pub struct RefInfo {
27 pub name: String,20 pub name: String,
28 pub full_name: String,21 pub full_name: String,
29- pub target: String, // peeled commit oid22+ pub target: String,
30 pub kind: RefKind,23 pub kind: RefKind,
31- pub committer_time: i64, // committer time of the target commit (unix seconds)24+ pub committer_time: i64,
32 }25 }
33 26
34 #[derive(Debug, Clone, Copy, PartialEq, Eq)]27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -76,15 +69,11 @@ fn gerr(e: impl std::fmt::Display) -> Error {
76 Error::Failed(e.to_string())69 Error::Failed(e.to_string())
77 }70 }
78 71
79-/// Every call opens a new handle, and gix's default delta-base cache is 96 MB per handle, so it is
80-/// capped here.
81 fn open(repo: &Path) -> Result<gix::Repository> {72 fn open(repo: &Path) -> Result<gix::Repository> {
82 let options = gix::open::Options::isolated().config_overrides(["core.deltaBaseCacheLimit=16m"]);73 let options = gix::open::Options::isolated().config_overrides(["core.deltaBaseCacheLimit=16m"]);
83 gix::open_opts(repo, options).map_err(gerr)74 gix::open_opts(repo, options).map_err(gerr)
84 }75 }
85 76
86-/// Git's ref-name rules (check-ref-format), plus rejection of anything that could be read as
87-/// revision syntax. Only names passing this are ever handed to gix.
88 fn valid_ref_name(name: &str) -> bool {77 fn valid_ref_name(name: &str) -> bool {
89 if name.is_empty() || name.len() > 255 || name == "@" {78 if name.is_empty() || name.len() > 255 || name == "@" {
90 return false;79 return false;
@@ -115,8 +104,6 @@ fn parse_oid(hex: &str) -> Result<gix::ObjectId> {
115 .map_err(|_| Error::InvalidInput(format!("not a full object id: {hex}")))104 .map_err(|_| Error::InvalidInput(format!("not a full object id: {hex}")))
116 }105 }
117 106
118-/// Commit id of `refs/heads/<name>` or `refs/tags/<name>` (tags peeled), if it exists and is a commit.
119-/// The name must already be validated.
120 fn ref_commit(repo: &gix::Repository, name: &str) -> Result<Option<gix::ObjectId>> {107 fn ref_commit(repo: &gix::Repository, name: &str) -> Result<Option<gix::ObjectId>> {
121 for prefix in ["refs/heads/", "refs/tags/"] {108 for prefix in ["refs/heads/", "refs/tags/"] {
122 let full = format!("{prefix}{name}");109 let full = format!("{prefix}{name}");
@@ -138,7 +125,6 @@ fn is_commit(repo: &gix::Repository, id: gix::ObjectId) -> Result<bool> {
138 ))125 ))
139 }126 }
140 127
141-/// Every branch and tag, with tags peeled to commits. Refs that do not peel to a commit are skipped.
142 pub fn list_refs(repo: &Path) -> Result<Vec<RefInfo>> {128 pub fn list_refs(repo: &Path) -> Result<Vec<RefInfo>> {
143 let repo = open(repo)?;129 let repo = open(repo)?;
144 let refs = repo.references().map_err(gerr)?;130 let refs = repo.references().map_err(gerr)?;
@@ -177,7 +163,6 @@ pub fn list_refs(repo: &Path) -> Result<Vec<RefInfo>> {
177 Ok(out)163 Ok(out)
178 }164 }
179 165
180-/// Commit at the tip of `refs/heads/<branch>`, or None if the branch does not exist.
181 pub fn default_branch_commit(repo: &Path, branch: &str) -> Result<Option<String>> {166 pub fn default_branch_commit(repo: &Path, branch: &str) -> Result<Option<String>> {
182 if !valid_ref_name(branch) {167 if !valid_ref_name(branch) {
183 return Ok(None);168 return Ok(None);
@@ -191,8 +176,6 @@ pub fn default_branch_commit(repo: &Path, branch: &str) -> Result<Option<String>
191 Ok(is_commit(&repo, id)?.then(|| id.to_hex().to_string()))176 Ok(is_commit(&repo, id)?.then(|| id.to_hex().to_string()))
192 }177 }
193 178
194-/// The commit a full object id names, peeling annotated tags (a pushed `git tag -a` points its
195-/// ref at a tag object). None when the object is missing or does not peel to a commit.
196 pub fn peel_to_commit(repo: &Path, oid: &str) -> Result<Option<String>> {179 pub fn peel_to_commit(repo: &Path, oid: &str) -> Result<Option<String>> {
197 let repo = open(repo)?;180 let repo = open(repo)?;
198 let Some(object) = repo.try_find_object(parse_oid(oid)?).map_err(gerr)? else {181 let Some(object) = repo.try_find_object(parse_oid(oid)?).map_err(gerr)? else {
@@ -204,15 +187,12 @@ pub fn peel_to_commit(repo: &Path, oid: &str) -> Result<Option<String>> {
204 .map(|c| c.id.to_hex().to_string()))187 .map(|c| c.id.to_hex().to_string()))
205 }188 }
206 189
207-/// Resolve user input to a full commit oid. Accepts a branch or tag name, or a 4-64 char hex prefix
208-/// that matches exactly one commit. Anything else resolves to None.
209 pub fn resolve_commit(repo: &Path, rev: &str) -> Result<Option<String>> {190 pub fn resolve_commit(repo: &Path, rev: &str) -> Result<Option<String>> {
210 if valid_ref_name(rev) {191 if valid_ref_name(rev) {
211 let repo = open(repo)?;192 let repo = open(repo)?;
212 if let Some(id) = ref_commit(&repo, rev)? {193 if let Some(id) = ref_commit(&repo, rev)? {
213 return Ok(Some(id.to_hex().to_string()));194 return Ok(Some(id.to_hex().to_string()));
214 }195 }
215- // A ref name that doesn't exist may still be a hex prefix below.
216 if !valid_hex_prefix(rev) {196 if !valid_hex_prefix(rev) {
217 return Ok(None);197 return Ok(None);
218 }198 }
@@ -233,14 +213,12 @@ fn resolve_hex(repo: &gix::Repository, hex: &str) -> Result<Option<String>> {
233 Some(Ok(id)) if is_commit(repo, id)? && reachable(repo, id)? => {213 Some(Ok(id)) if is_commit(repo, id)? && reachable(repo, id)? => {
234 Ok(Some(id.to_hex().to_string()))214 Ok(Some(id.to_hex().to_string()))
235 }215 }
236- _ => Ok(None), // missing, ambiguous, overwritten, or not a commit216+ _ => Ok(None),
237 }217 }
238 }218 }
239 219
240-/// The refs whose history is public. A commit no ref here reaches was overwritten or deleted.
241 const VISIBLE_REFS: [&str; 3] = ["refs/heads/", "refs/tags/", "refs/pull/"];220 const VISIBLE_REFS: [&str; 3] = ["refs/heads/", "refs/tags/", "refs/pull/"];
242 221
243-/// The commits at the tips of [`VISIBLE_REFS`]. A ref that does not peel to a commit reaches nothing.
244 fn visible_tips(repo: &gix::Repository) -> Result<Vec<gix::ObjectId>> {222 fn visible_tips(repo: &gix::Repository) -> Result<Vec<gix::ObjectId>> {
245 let refs = repo.references().map_err(gerr)?;223 let refs = repo.references().map_err(gerr)?;
246 let mut tips = Vec::new();224 let mut tips = Vec::new();
@@ -258,8 +236,6 @@ fn visible_tips(repo: &gix::Repository) -> Result<Vec<gix::ObjectId>> {
258 Ok(tips)236 Ok(tips)
259 }237 }
260 238
261-/// True when a branch, tag or pull request reaches `id`. Other commits stay on disk until
262-/// `maintenance::prune_unreachable` runs, and must not be served by hash until then.
263 fn reachable(repo: &gix::Repository, id: gix::ObjectId) -> Result<bool> {239 fn reachable(repo: &gix::Repository, id: gix::ObjectId) -> Result<bool> {
264 let tips = visible_tips(repo)?;240 let tips = visible_tips(repo)?;
265 if tips.contains(&id) {241 if tips.contains(&id) {
@@ -276,8 +252,6 @@ fn reachable(repo: &gix::Repository, id: gix::ObjectId) -> Result<bool> {
276 Ok(false)252 Ok(false)
277 }253 }
278 254
279-/// Those of the full commit ids `oids` that a branch, tag or pull request reaches, in one walk.
280-/// Malformed ids are left out. For deciding which stored hashes on a page may still link.
281 pub fn reachable_commits(repo: &Path, oids: &[String]) -> Result<HashSet<String>> {255 pub fn reachable_commits(repo: &Path, oids: &[String]) -> Result<HashSet<String>> {
282 let mut wanted: HashSet<gix::ObjectId> =256 let mut wanted: HashSet<gix::ObjectId> =
283 oids.iter().filter_map(|oid| parse_oid(oid).ok()).collect();257 oids.iter().filter_map(|oid| parse_oid(oid).ok()).collect();
@@ -300,15 +274,12 @@ pub fn reachable_commits(repo: &Path, oids: &[String]) -> Result<HashSet<String>
300 Ok(found)274 Ok(found)
301 }275 }
302 276
303-/// True when `oid` is a full commit id that a branch, tag or pull request reaches.
304 pub fn commit_reachable(repo: &Path, oid: &str) -> Result<bool> {277 pub fn commit_reachable(repo: &Path, oid: &str) -> Result<bool> {
305 let repo = open(repo)?;278 let repo = open(repo)?;
306 let id = parse_oid(oid)?;279 let id = parse_oid(oid)?;
307 Ok(is_commit(&repo, id)? && reachable(&repo, id)?)280 Ok(is_commit(&repo, id)? && reachable(&repo, id)?)
308 }281 }
309 282
310-/// Split `"feature/x/src/main.rs"` into `("feature/x", commit, "src/main.rs")`. The longest existing
311-/// branch or tag prefix wins. Otherwise a leading hex segment is taken as a commit prefix.
312 pub fn split_ref_and_path(repo: &Path, rest: &str) -> Result<Option<(String, String, String)>> {283 pub fn split_ref_and_path(repo: &Path, rest: &str) -> Result<Option<(String, String, String)>> {
313 let segments: Vec<&str> = rest.split('/').collect();284 let segments: Vec<&str> = rest.split('/').collect();
314 let repo = open(repo)?;285 let repo = open(repo)?;
@@ -360,8 +331,6 @@ fn commit_root<'r>(repo: &'r gix::Repository, commit: &str) -> Result<Option<gix
360 ))331 ))
361 }332 }
362 333
363-/// Tree object for `commit` at `path` ("" is the root). Ok(None) if the commit is missing or the
364-/// path does not exist. A path that is a blob also yields None.
365 fn tree_at<'r>(334 fn tree_at<'r>(
366 repo: &'r gix::Repository,335 repo: &'r gix::Repository,
367 commit: &str,336 commit: &str,
@@ -387,7 +356,6 @@ fn tree_at<'r>(
387 Ok(Some(tree))356 Ok(Some(tree))
388 }357 }
389 358
390-/// Directory listing at `path` in `commit`: directories first, then names in bytewise order.
391 pub fn read_tree(repo: &Path, commit: &str, path: &str) -> Result<Option<Vec<TreeEntry>>> {359 pub fn read_tree(repo: &Path, commit: &str, path: &str) -> Result<Option<Vec<TreeEntry>>> {
392 validate_repo_path(path)?;360 validate_repo_path(path)?;
393 let repo = open(repo)?;361 let repo = open(repo)?;
@@ -418,12 +386,6 @@ pub fn read_tree(repo: &Path, commit: &str, path: &str) -> Result<Option<Vec<Tre
418 Ok(Some(entries))386 Ok(Some(entries))
419 }387 }
420 388
421-/// Blob at `path` in `commit`, with at most `max_bytes` of data. Symlinks yield their target text.
422-/// Submodules yield an empty entry (their target commit is not in this repo). Trees and missing
423-/// paths yield None.
424-///
425-/// Note: gix offers no public streaming read for packed objects, so the whole blob is loaded and
426-/// then truncated to `max_bytes`.
427 pub fn read_blob(389 pub fn read_blob(
428 repo: &Path,390 repo: &Path,
429 commit: &str,391 commit: &str,
@@ -433,7 +395,6 @@ pub fn read_blob(
433 blob_at(repo, commit, path, max_bytes, false)395 blob_at(repo, commit, path, max_bytes, false)
434 }396 }
435 397
436-/// `text_only` makes a blob larger than `max_bytes` yield None before its data is loaded.
437 fn blob_at(398 fn blob_at(
438 repo: &Path,399 repo: &Path,
439 commit: &str,400 commit: &str,
@@ -474,7 +435,6 @@ fn blob_at(
474 let is_binary = data[..data.len().min(BINARY_PROBE_BYTES)].contains(&0);435 let is_binary = data[..data.len().min(BINARY_PROBE_BYTES)].contains(&0);
475 let truncated = data.len() > max_bytes;436 let truncated = data.len() > max_bytes;
476 if truncated {437 if truncated {
477- // Give back the memory of the dropped tail, not just its length.
478 data.truncate(max_bytes);438 data.truncate(max_bytes);
479 data.shrink_to_fit();439 data.shrink_to_fit();
480 }440 }
@@ -490,8 +450,6 @@ fn blob_at(
490 }450 }
491 }451 }
492 452
493-/// The text of the regular file at `path` in `commit`. None when the path is missing, is not a
494-/// regular file or symlink, is binary, is not valid UTF-8, or is larger than `max_bytes`.
495 pub fn read_text_blob(453 pub fn read_text_blob(
496 repo: &Path,454 repo: &Path,
497 commit: &str,455 commit: &str,
@@ -511,7 +469,6 @@ fn lossy(bytes: &[u8]) -> String {
511 String::from_utf8_lossy(bytes).into_owned()469 String::from_utf8_lossy(bytes).into_owned()
512 }470 }
513 471
514-/// Metadata and message of a commit. Ok(None) if the object is missing or not a commit.
515 pub fn read_commit(repo: &Path, oid: &str) -> Result<Option<CommitInfo>> {472 pub fn read_commit(repo: &Path, oid: &str) -> Result<Option<CommitInfo>> {
516 let repo = open(repo)?;473 let repo = open(repo)?;
517 let id = parse_oid(oid)?;474 let id = parse_oid(oid)?;
@@ -538,8 +495,6 @@ pub fn read_commit(repo: &Path, oid: &str) -> Result<Option<CommitInfo>> {
538 }))495 }))
539 }496 }
540 497
541-/// Rules for `/`-separated repo paths: no empty, `.` or `..` segment, no NUL, at most 4096 bytes.
542-/// The empty path (the root) is valid.
543 pub fn validate_repo_path(path: &str) -> Result<()> {498 pub fn validate_repo_path(path: &str) -> Result<()> {
544 if path.len() > MAX_PATH_BYTES {499 if path.len() > MAX_PATH_BYTES {
545 return Err(Error::InvalidInput("path too long".into()));500 return Err(Error::InvalidInput("path too long".into()));
crates/forge-git/src/churn.rsmodified+0 -16
@@ -1,7 +1,3 @@
1-//! Lines changed per commit, for the history strip on the repo page and the CI page: the newest
2-//! commits reachable from a commit, each counted against its first parent. One `git log` run with
3-//! `--shortstat`, so the output is a few bytes per commit however big the commits are.
4-
5 use std::path::Path;1 use std::path::Path;
6 use std::time::Duration;2 use std::time::Duration;
7 3
@@ -9,24 +5,16 @@ use crate::command::GitEnv;
9 use crate::error::{Error, Result};5 use crate::error::{Error, Result};
10 use crate::history::{git, read_capped, validate_oid};6 use crate::history::{git, read_capped, validate_oid};
11 7
12-/// Most commits one call returns.
13 pub const MAX_COMMITS: usize = 48;8 pub const MAX_COMMITS: usize = 48;
14-/// Longest a single walk may take. A huge commit is one diff for git to count, so this bounds the
15-/// page's wait; the child is killed when the timeout drops the read.
16 const WALK_TIMEOUT: Duration = Duration::from_secs(5);9 const WALK_TIMEOUT: Duration = Duration::from_secs(5);
17-/// Record start in the `log` format, so a commit's header can be told from its stat line.
18 const REC: u8 = 0x1e;10 const REC: u8 = 0x1e;
19 11
20-/// One commit and the lines it changed: additions plus deletions against its first parent.
21-/// A root commit counts against the empty tree. Binary files add nothing to the count.
22 #[derive(Debug, Clone, PartialEq, Eq)]12 #[derive(Debug, Clone, PartialEq, Eq)]
23 pub struct CommitChurn {13 pub struct CommitChurn {
24 pub oid: String,14 pub oid: String,
25 pub lines: u64,15 pub lines: u64,
26 }16 }
27 17
28-/// The newest `limit` commits reachable from `head` (a full object id), newest first, capped at
29-/// [`MAX_COMMITS`]. Merge commits count their diff against the first parent only.
30 pub async fn recent_churn(18 pub async fn recent_churn(
31 env: &GitEnv,19 env: &GitEnv,
32 repo: &Path,20 repo: &Path,
@@ -54,8 +42,6 @@ pub async fn recent_churn(
54 Ok(parse(&read.0))42 Ok(parse(&read.0))
55 }43 }
56 44
57-/// Splits `log` output into records. Each record is one commit id, then its stat line when the
58-/// commit changed anything.
59 fn parse(buf: &[u8]) -> Vec<CommitChurn> {45 fn parse(buf: &[u8]) -> Vec<CommitChurn> {
60 buf.split(|&b| b == REC)46 buf.split(|&b| b == REC)
61 .filter_map(|rec| {47 .filter_map(|rec| {
@@ -72,8 +58,6 @@ fn parse(buf: &[u8]) -> Vec<CommitChurn> {
72 .collect()58 .collect()
73 }59 }
74 60
75-/// The insertions plus deletions in one `--shortstat` line, such as
76-/// " 3 files changed, 10 insertions(+), 2 deletions(-)". Zero for any other line.
77 fn stat_line_total(line: &str) -> u64 {61 fn stat_line_total(line: &str) -> u64 {
78 if !line.contains("changed") {62 if !line.contains("changed") {
79 return 0;63 return 0;
crates/forge-git/src/command.rsmodified+0 -38
@@ -1,28 +1,20 @@
1-//! Builder for `git` invocations. Never uses a shell. Cleared environment.
2-
3 use std::ffi::{OsStr, OsString};1 use std::ffi::{OsStr, OsString};
4 use std::path::{Path, PathBuf};2 use std::path::{Path, PathBuf};
5 use std::process::{Output, Stdio};3 use std::process::{Output, Stdio};
6 4
7 use crate::error::{Error, Result};5 use crate::error::{Error, Result};
8 6
9-/// Where git lives and where forge keeps its managed config and hooks.
10-/// Gitconfig at `data_dir/gitconfig`, hooks at `data_dir/hooks`.
11 #[derive(Debug, Clone)]7 #[derive(Debug, Clone)]
12 pub struct GitEnv {8 pub struct GitEnv {
13 pub git_bin: PathBuf,9 pub git_bin: PathBuf,
14 pub data_dir: PathBuf,10 pub data_dir: PathBuf,
15 }11 }
16 12
17-/// Extra object directory that a read-only command may read from, besides its own repo. Used to
18-/// compare a fork's commits without copying them into the base repo. Never built from user input.
19 #[derive(Debug, Clone, Copy, Default)]13 #[derive(Debug, Clone, Copy, Default)]
20 pub struct ObjectSource<'a> {14 pub struct ObjectSource<'a> {
21 pub extra: Option<&'a Path>,15 pub extra: Option<&'a Path>,
22 }16 }
23 17
24-/// Builds a `git` command. Only trusted static flags go through [`GitCommand::arg`];
25-/// user input only through the `user_*` methods and [`GitCommand::paths`].
26 #[derive(Debug)]18 #[derive(Debug)]
27 pub struct GitCommand {19 pub struct GitCommand {
28 program: PathBuf,20 program: PathBuf,
@@ -32,11 +24,9 @@ pub struct GitCommand {
32 envs: Vec<(&'static str, OsString)>,24 envs: Vec<(&'static str, OsString)>,
33 end_of_options: bool,25 end_of_options: bool,
34 local_transport: bool,26 local_transport: bool,
35- /// `key=value` pairs passed as `-c` before the subcommand. Static text only.
36 configs: Vec<String>,27 configs: Vec<String>,
37 }28 }
38 29
39-/// Rejects user values that git could read as an option, or that cannot be passed as argv.
40 fn check_user_value(v: &str) -> Result<()> {30 fn check_user_value(v: &str) -> Result<()> {
41 if v.is_empty() {31 if v.is_empty() {
42 return Err(Error::InvalidInput("empty value".into()));32 return Err(Error::InvalidInput("empty value".into()));
@@ -51,9 +41,6 @@ fn check_user_value(v: &str) -> Result<()> {
51 }41 }
52 42
53 impl GitCommand {43 impl GitCommand {
54- /// Sets the child environment: `PATH`, `HOME=data_dir`, `GIT_CONFIG_NOSYSTEM=1`,
55- /// `GIT_CONFIG_GLOBAL=data_dir/gitconfig`, `GIT_TERMINAL_PROMPT=0`, `LANG=C`.
56- /// The environment is cleared before these are applied, in [`GitCommand::into_tokio`].
57 pub fn new(env: &GitEnv, subcommand: &'static str) -> Self {44 pub fn new(env: &GitEnv, subcommand: &'static str) -> Self {
58 let envs = vec![45 let envs = vec![
59 ("PATH", OsString::from("/usr/local/bin:/usr/bin:/bin")),46 ("PATH", OsString::from("/usr/local/bin:/usr/bin:/bin")),
@@ -78,14 +65,11 @@ impl GitCommand {
78 }65 }
79 }66 }
80 67
81- /// Adds a `-c key=value` before the subcommand. Only trusted static text goes here.
82 pub fn config(mut self, kv: &'static str) -> Self {68 pub fn config(mut self, kv: &'static str) -> Self {
83 self.configs.push(kv.to_string());69 self.configs.push(kv.to_string());
84 self70 self
85 }71 }
86 72
87- /// Adds a `-c key=value` whose value was built at run time, such as a pinned address. Rejects a
88- /// pair with no `=`, or with whitespace or control characters.
89 pub fn config_checked(mut self, kv: String) -> Result<Self> {73 pub fn config_checked(mut self, kv: String) -> Result<Self> {
90 if !kv.contains('=') || kv.chars().any(|c| c.is_whitespace() || c.is_control()) {74 if !kv.contains('=') || kv.chars().any(|c| c.is_whitespace() || c.is_control()) {
91 return Err(Error::InvalidInput("invalid git config pair".into()));75 return Err(Error::InvalidInput("invalid git config pair".into()));
@@ -94,13 +78,11 @@ impl GitCommand {
94 Ok(self)78 Ok(self)
95 }79 }
96 80
97- /// Appends a trusted static flag.
98 pub fn arg(mut self, a: &'static str) -> Self {81 pub fn arg(mut self, a: &'static str) -> Self {
99 self.args.push(OsString::from(a));82 self.args.push(OsString::from(a));
100 self83 self
101 }84 }
102 85
103- /// Adds `--git-dir=<p>`, placed before the subcommand.
104 pub fn git_dir(mut self, p: &Path) -> Self {86 pub fn git_dir(mut self, p: &Path) -> Self {
105 let mut s = OsString::from("--git-dir=");87 let mut s = OsString::from("--git-dir=");
106 s.push(p.as_os_str());88 s.push(p.as_os_str());
@@ -108,17 +90,11 @@ impl GitCommand {
108 self90 self
109 }91 }
110 92
111- /// Allows git's `file` transport (local paths) for this one invocation, by passing
112- /// `-c protocol.file.allow=always` ahead of the subcommand. The managed gitconfig sets
113- /// `protocol.file.allow = never` to keep user-controlled URLs out of local paths, so only the
114- /// call sites that open repositories forge itself chose may use this. Only pass paths produced
115- /// by `repo_path()` or the server's own data dir, never user input.
116 pub fn allow_local_transport(mut self) -> Self {93 pub fn allow_local_transport(mut self) -> Self {
117 self.local_transport = true;94 self.local_transport = true;
118 self95 self
119 }96 }
120 97
121- /// Appends `--end-of-options` (once) and the revs. Rejects empty revs and revs starting with `-`.
122 pub fn user_revs(mut self, revs: &[&str]) -> Result<Self> {98 pub fn user_revs(mut self, revs: &[&str]) -> Result<Self> {
123 for r in revs {99 for r in revs {
124 check_user_value(r)?;100 check_user_value(r)?;
@@ -131,15 +107,12 @@ impl GitCommand {
131 Ok(self)107 Ok(self)
132 }108 }
133 109
134- /// Appends one validated user value as a positional argument (no separator).
135 pub fn user_arg(mut self, v: &str) -> Result<Self> {110 pub fn user_arg(mut self, v: &str) -> Result<Self> {
136 check_user_value(v)?;111 check_user_value(v)?;
137 self.args.push(OsString::from(v));112 self.args.push(OsString::from(v));
138 Ok(self)113 Ok(self)
139 }114 }
140 115
141- /// Appends `-e <pattern>`. The value follows `-e`, so git reads it as a pattern even when it
142- /// starts with `-`. Rejects empty patterns and NUL.
143 pub fn user_pattern(mut self, pattern: &str) -> Result<Self> {116 pub fn user_pattern(mut self, pattern: &str) -> Result<Self> {
144 if pattern.is_empty() {117 if pattern.is_empty() {
145 return Err(Error::InvalidInput("empty pattern".into()));118 return Err(Error::InvalidInput("empty pattern".into()));
@@ -152,14 +125,12 @@ impl GitCommand {
152 Ok(self)125 Ok(self)
153 }126 }
154 127
155- /// Appends one validated `--flag=value` argument, e.g. `("--initial-branch", "main")`.
156 pub fn user_opt(mut self, flag: &'static str, v: &str) -> Result<Self> {128 pub fn user_opt(mut self, flag: &'static str, v: &str) -> Result<Self> {
157 check_user_value(v)?;129 check_user_value(v)?;
158 self.args.push(OsString::from(format!("{flag}={v}")));130 self.args.push(OsString::from(format!("{flag}={v}")));
159 Ok(self)131 Ok(self)
160 }132 }
161 133
162- /// Appends `--` and the paths.
163 pub fn paths(mut self, paths: &[&str]) -> Self {134 pub fn paths(mut self, paths: &[&str]) -> Self {
164 self.args.push(OsString::from("--"));135 self.args.push(OsString::from("--"));
165 self.args.extend(paths.iter().map(OsString::from));136 self.args.extend(paths.iter().map(OsString::from));
@@ -171,10 +142,6 @@ impl GitCommand {
171 self142 self
172 }143 }
173 144
174- /// Lets this command read objects from `dir` as well, through `GIT_ALTERNATE_OBJECT_DIRECTORIES`.
175- /// The variable is set on this child process only. Git writes nothing there, so use it only for
176- /// read-only subcommands. `dir` must be an absolute existing directory whose path has no `:`
177- /// (git's list separator) and no newline.
178 pub fn alternate_objects(mut self, dir: &Path) -> Result<Self> {145 pub fn alternate_objects(mut self, dir: &Path) -> Result<Self> {
179 let text = dir146 let text = dir
180 .to_str()147 .to_str()
@@ -192,7 +159,6 @@ impl GitCommand {
192 Ok(self)159 Ok(self)
193 }160 }
194 161
195- /// Applies an [`ObjectSource`]: adds its extra object directory, if it has one.
196 pub fn objects(self, src: ObjectSource<'_>) -> Result<Self> {162 pub fn objects(self, src: ObjectSource<'_>) -> Result<Self> {
197 match src.extra {163 match src.extra {
198 Some(dir) => self.alternate_objects(dir),164 Some(dir) => self.alternate_objects(dir),
@@ -222,7 +188,6 @@ impl GitCommand {
222 cmd188 cmd
223 }189 }
224 190
225- /// Runs the command and returns stdout. A non-zero exit becomes `Error::Failed` with stderr.
226 pub async fn output(self) -> Result<Vec<u8>> {191 pub async fn output(self) -> Result<Vec<u8>> {
227 let subcommand = self.subcommand;192 let subcommand = self.subcommand;
228 let out = self.into_tokio().output().await?;193 let out = self.into_tokio().output().await?;
@@ -230,8 +195,6 @@ impl GitCommand {
230 Ok(out.stdout)195 Ok(out.stdout)
231 }196 }
232 197
233- /// Runs the command with `input` on stdin and returns stdout. Used by plumbing such as
234- /// `hash-object --stdin` and `commit-tree -F -`, where the content is not an argument.
235 pub async fn output_stdin(self, input: &[u8]) -> Result<Vec<u8>> {198 pub async fn output_stdin(self, input: &[u8]) -> Result<Vec<u8>> {
236 use tokio::io::AsyncWriteExt;199 use tokio::io::AsyncWriteExt;
237 200
@@ -250,7 +213,6 @@ impl GitCommand {
250 Ok(out.stdout)213 Ok(out.stdout)
251 }214 }
252 215
253- /// Runs the command and discards stdout. A non-zero exit becomes `Error::Failed` with stderr.
254 pub async fn status(self) -> Result<()> {216 pub async fn status(self) -> Result<()> {
255 self.output().await.map(|_| ())217 self.output().await.map(|_| ())
256 }218 }
crates/forge-git/src/error.rsmodified+0 -3
@@ -1,5 +1,3 @@
1-//! Errors for the git layer. Converted to `forge_core::Error` at crate boundaries.
2-
3 #[derive(Debug, thiserror::Error)]1 #[derive(Debug, thiserror::Error)]
4 pub enum Error {2 pub enum Error {
5 #[error("io error: {0}")]3 #[error("io error: {0}")]
@@ -12,7 +10,6 @@ pub enum Error {
12 InvalidInput(String),10 InvalidInput(String),
13 #[error("git command failed: {0}")]11 #[error("git command failed: {0}")]
14 Failed(String),12 Failed(String),
15- /// A compare-and-swap ref update found the ref at a different value than expected.
16 #[error("ref moved since it was read: {0}")]13 #[error("ref moved since it was read: {0}")]
17 RefMoved(String),14 RefMoved(String),
18 }15 }
crates/forge-git/src/fsck.rsmodified+0 -12
@@ -1,5 +1,3 @@
1-//! `git fsck` on one repo: the integrity check behind the scheduled and manual fsck runs.
2-
3 use std::path::Path;1 use std::path::Path;
4 2
5 use std::process::Stdio;3 use std::process::Stdio;
@@ -8,22 +6,15 @@ use crate::command::{GitCommand, GitEnv};
8 use crate::error::Result;6 use crate::error::Result;
9 use crate::history::read_pipe_head;7 use crate::history::read_pipe_head;
10 8
11-/// Longest git output kept, in bytes.
12 const MAX_OUTPUT_BYTES: usize = 64 * 1024;9 const MAX_OUTPUT_BYTES: usize = 64 * 1024;
13 10
14-/// Outcome of [`fsck`]. `output` holds git's diagnostics (stdout and stderr, trimmed, at most
15-/// 64 KiB). It is empty when the repo is clean.
16 #[derive(Debug, Clone, PartialEq, Eq)]11 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct FsckReport {12 pub struct FsckReport {
18 pub ok: bool,13 pub ok: bool,
19 pub output: String,14 pub output: String,
20 }15 }
21 16
22-/// Runs `git fsck` (with `--full` when asked) on the repo at `repo`. A repo git cannot open, or
23-/// one with damaged objects, is a report with `ok` false, not an error. Only a failure to start
24-/// git is an error.
25 pub async fn fsck(env: &GitEnv, repo: &Path, full: bool) -> Result<FsckReport> {17 pub async fn fsck(env: &GitEnv, repo: &Path, full: bool) -> Result<FsckReport> {
26- // Dangling objects are not problems and would only pad the output.
27 let mut cmd = GitCommand::new(env, "fsck")18 let mut cmd = GitCommand::new(env, "fsck")
28 .git_dir(repo)19 .git_dir(repo)
29 .arg("--no-dangling");20 .arg("--no-dangling");
@@ -43,7 +34,6 @@ pub async fn fsck(env: &GitEnv, repo: &Path, full: bool) -> Result<FsckReport> {
43 for task in [stdout, stderr].into_iter().flatten() {34 for task in [stdout, stderr].into_iter().flatten() {
44 text.push_str(&String::from_utf8_lossy(&task.await.unwrap_or_default()));35 text.push_str(&String::from_utf8_lossy(&task.await.unwrap_or_default()));
45 }36 }
46- // Each pipe keeps its own head, so the two together can exceed the cap.
47 let mut end = text.len().min(MAX_OUTPUT_BYTES);37 let mut end = text.len().min(MAX_OUTPUT_BYTES);
48 while !text.is_char_boundary(end) {38 while !text.is_char_boundary(end) {
49 end -= 1;39 end -= 1;
@@ -91,7 +81,6 @@ mod tests {
91 let clean = fsck(&env(dir.path()), &git_dir, true).await.expect("fsck");81 let clean = fsck(&env(dir.path()), &git_dir, true).await.expect("fsck");
92 assert!(clean.ok, "{}", clean.output);82 assert!(clean.ok, "{}", clean.output);
93 83
94- // Corrupt the only loose object: fsck must report it, not error out.
95 let head = Command::new("git")84 let head = Command::new("git")
96 .current_dir(&work)85 .current_dir(&work)
97 .args(["rev-parse", "HEAD"])86 .args(["rev-parse", "HEAD"])
@@ -99,7 +88,6 @@ mod tests {
99 .expect("rev-parse");88 .expect("rev-parse");
100 let oid = String::from_utf8_lossy(&head.stdout).trim().to_owned();89 let oid = String::from_utf8_lossy(&head.stdout).trim().to_owned();
101 let object = git_dir.join("objects").join(&oid[..2]).join(&oid[2..]);90 let object = git_dir.join("objects").join(&oid[..2]).join(&oid[2..]);
102- // Git stores loose objects read-only, so replace the file rather than writing into it.
103 std::fs::remove_file(&object).expect("remove object");91 std::fs::remove_file(&object).expect("remove object");
104 std::fs::write(&object, b"not zlib").expect("corrupt");92 std::fs::write(&object, b"not zlib").expect("corrupt");
105 let damaged = fsck(&env(dir.path()), &git_dir, false).await.expect("fsck");93 let damaged = fsck(&env(dir.path()), &git_dir, false).await.expect("fsck");
crates/forge-git/src/lib.rsmodified+0 -2
@@ -1,5 +1,3 @@
1-//! Git plumbing for forge: a safe command builder, repo management and smart-HTTP helpers.
2-
3 pub mod backup;1 pub mod backup;
4 pub mod blame;2 pub mod blame;
5 pub mod branches;3 pub mod branches;
crates/forge-git/src/maintenance.rsmodified+0 -29
@@ -1,6 +1,3 @@
1-//! Post-push housekeeping for a bare repository: commit-graph refresh and `git maintenance --auto`,
2-//! and removing what a force push or a deleted ref left behind.
3-
4 use std::fs;1 use std::fs;
5 use std::path::Path;2 use std::path::Path;
6 use std::time::{Duration, SystemTime};3 use std::time::{Duration, SystemTime};
@@ -8,27 +5,15 @@ use std::time::{Duration, SystemTime};
8 use crate::command::{GitCommand, GitEnv};5 use crate::command::{GitCommand, GitEnv};
9 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
10 7
11-/// Upper bound for each git invocation. The child is killed when the timeout fires.
12 const STEP_TIMEOUT: Duration = Duration::from_secs(120);8 const STEP_TIMEOUT: Duration = Duration::from_secs(120);
13-/// Upper bound for one prune, which repacks the repo.
14 const PRUNE_TIMEOUT: Duration = Duration::from_secs(30 * 60);9 const PRUNE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
15-/// Written in the bare repo when history was overwritten or deleted. A file, so a restart keeps it.
16 const PRUNE_MARK: &str = "forge-prune-due";10 const PRUNE_MARK: &str = "forge-prune-due";
17-/// Touched after each prune.
18 const PRUNE_STAMP: &str = "forge-pruned";11 const PRUNE_STAMP: &str = "forge-pruned";
19-/// Written after a prune removed objects. The standby still holds them, so its next replication
20-/// prunes its copy and clears this mark.
21 const STANDBY_PRUNE_MARK: &str = "forge-standby-prune-due";12 const STANDBY_PRUNE_MARK: &str = "forge-standby-prune-due";
22-/// A push's objects are unreachable for a moment before its ref lands, so only objects at least
23-/// this old are removed. The mark waits this long too, so everything it stands for qualifies.
24 const PRUNE_GRACE: Duration = Duration::from_secs(15 * 60);13 const PRUNE_GRACE: Duration = Duration::from_secs(15 * 60);
25-/// The `git gc` flag for [`PRUNE_GRACE`].
26 pub const PRUNE_AFTER_GRACE: &str = "--prune=900.seconds.ago";14 pub const PRUNE_AFTER_GRACE: &str = "--prune=900.seconds.ago";
27-/// Every repo is pruned this often, for what no mark covers: mirrors and a fork's old pull heads.
28 const PRUNE_EVERY: Duration = Duration::from_secs(7 * 24 * 60 * 60);15 const PRUNE_EVERY: Duration = Duration::from_secs(7 * 24 * 60 * 60);
29 16
30-/// Refreshes the commit-graph (with changed-path filters) and runs the auto maintenance tasks
31-/// for the bare repo at `repo`. Each step is bounded by [`STEP_TIMEOUT`].
32 pub async fn after_push(env: &GitEnv, repo: &Path) -> Result<()> {17 pub async fn after_push(env: &GitEnv, repo: &Path) -> Result<()> {
33 let graph = GitCommand::new(env, "commit-graph")18 let graph = GitCommand::new(env, "commit-graph")
34 .git_dir(repo)19 .git_dir(repo)
@@ -45,14 +30,10 @@ pub async fn after_push(env: &GitEnv, repo: &Path) -> Result<()> {
45 run_bounded(maintenance).await30 run_bounded(maintenance).await
46 }31 }
47 32
48-/// Records that `repo` has overwritten or deleted history to remove. Best effort: a missed mark
49-/// waits for the weekly prune.
50 pub fn mark_prune_due(repo: &Path) {33 pub fn mark_prune_due(repo: &Path) {
51 let _ = fs::write(repo.join(PRUNE_MARK), b"");34 let _ = fs::write(repo.join(PRUNE_MARK), b"");
52 }35 }
53 36
54-/// True when `repo` should be pruned now: its mark is past the grace period, or it was not pruned
55-/// in the last week, which includes never.
56 pub fn prune_due(repo: &Path, now: SystemTime) -> bool {37 pub fn prune_due(repo: &Path, now: SystemTime) -> bool {
57 let age = |name: &str| {38 let age = |name: &str| {
58 let modified = fs::metadata(repo.join(name))39 let modified = fs::metadata(repo.join(name))
@@ -64,8 +45,6 @@ pub fn prune_due(repo: &Path, now: SystemTime) -> bool {
64 || age(PRUNE_STAMP).is_none_or(|stamp| stamp >= PRUNE_EVERY)45 || age(PRUNE_STAMP).is_none_or(|stamp| stamp >= PRUNE_EVERY)
65 }46 }
66 47
67-/// Deletes the objects no ref reaches, of the age `prune` names. A hash overwritten by a force push
68-/// or left by a deleted ref can then no longer be fetched, which git would otherwise allow.
69 pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -> Result<()> {48 pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -> Result<()> {
70 let marked = fs::metadata(repo.join(PRUNE_MARK)).and_then(|m| m.modified());49 let marked = fs::metadata(repo.join(PRUNE_MARK)).and_then(|m| m.modified());
71 let gc = GitCommand::new(env, "gc")50 let gc = GitCommand::new(env, "gc")
@@ -83,7 +62,6 @@ pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -
83 }62 }
84 fs::write(repo.join(PRUNE_STAMP), b"")?;63 fs::write(repo.join(PRUNE_STAMP), b"")?;
85 fs::write(repo.join(STANDBY_PRUNE_MARK), b"")?;64 fs::write(repo.join(STANDBY_PRUNE_MARK), b"")?;
86- // A mark written during the prune stays for the next pass.
87 if let Ok(marked) = marked65 if let Ok(marked) = marked
88 && fs::metadata(repo.join(PRUNE_MARK))66 && fs::metadata(repo.join(PRUNE_MARK))
89 .and_then(|m| m.modified())67 .and_then(|m| m.modified())
@@ -95,19 +73,14 @@ pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -
95 Ok(())73 Ok(())
96 }74 }
97 75
98-/// True when a prune removed objects that the standby copy of `repo` still holds.
99 pub fn standby_prune_due(repo: &Path) -> bool {76 pub fn standby_prune_due(repo: &Path) -> bool {
100 repo.join(STANDBY_PRUNE_MARK).is_file()77 repo.join(STANDBY_PRUNE_MARK).is_file()
101 }78 }
102 79
103-/// Clears the standby mark once the standby has been pruned. Best effort: a mark left behind only
104-/// causes one more harmless prune.
105 pub fn clear_standby_prune(repo: &Path) {80 pub fn clear_standby_prune(repo: &Path) {
106 let _ = fs::remove_file(repo.join(STANDBY_PRUNE_MARK));81 let _ = fs::remove_file(repo.join(STANDBY_PRUNE_MARK));
107 }82 }
108 83
109-/// Runs `cmd` with [`STEP_TIMEOUT`]. Dropping the future on timeout drops the child,
110-/// which `GitCommand` spawns with `kill_on_drop`, so the process is killed.
111 async fn run_bounded(cmd: GitCommand) -> Result<()> {84 async fn run_bounded(cmd: GitCommand) -> Result<()> {
112 match tokio::time::timeout(STEP_TIMEOUT, cmd.status()).await {85 match tokio::time::timeout(STEP_TIMEOUT, cmd.status()).await {
113 Ok(result) => result,86 Ok(result) => result,
@@ -177,7 +150,6 @@ mod tests {
177 bare.display()150 bare.display()
178 );151 );
179 152
180- // A second run on an unchanged repo must also succeed.
181 after_push(&env, &bare).await.expect("second after_push");153 after_push(&env, &bare).await.expect("second after_push");
182 }154 }
183 155
@@ -216,7 +188,6 @@ mod tests {
216 assert_eq!(resolve_commit(&bare, &old).unwrap(), None);188 assert_eq!(resolve_commit(&bare, &old).unwrap(), None);
217 assert!(!commit_reachable(&bare, &old).unwrap());189 assert!(!commit_reachable(&bare, &old).unwrap());
218 190
219- // A pull request's ref keeps its commit visible and on disk.
220 git(&bare, &["update-ref", "refs/pull/1/head", &old]);191 git(&bare, &["update-ref", "refs/pull/1/head", &old]);
221 assert_eq!(resolve_commit(&bare, &old).unwrap(), Some(old.clone()));192 assert_eq!(resolve_commit(&bare, &old).unwrap(), Some(old.clone()));
222 git(&bare, &["update-ref", "-d", "refs/pull/1/head"]);193 git(&bare, &["update-ref", "-d", "refs/pull/1/head"]);
crates/forge-git/src/mirror.rsmodified+0 -49
@@ -1,11 +1,3 @@
1-//! Pull and push mirrors: `git fetch` from a remote URL into a repo, and `git push` of a repo's
2-//! refs to a remote URL. Only `refs/heads/*` and `refs/tags/*` are synced, with prune.
3-//!
4-//! Safety for every remote call: protocols are limited to https (and http when the caller allows
5-//! it), redirects are not followed, no credential helper runs, and a prompt is never shown. The
6-//! credentials travel only in the child environment (`GIT_CONFIG_*` for an `http.extraHeader`),
7-//! never in argv, the URL or an error. Errors are scrubbed before they leave this module.
8-
9 use std::fmt;1 use std::fmt;
10 use std::future::Future;2 use std::future::Future;
11 use std::net::IpAddr;3 use std::net::IpAddr;
@@ -18,15 +10,11 @@ use base64::engine::general_purpose::STANDARD;
18 use crate::command::{GitCommand, GitEnv};10 use crate::command::{GitCommand, GitEnv};
19 use crate::error::{Error, Result};11 use crate::error::{Error, Result};
20 12
21-/// The refspecs both directions sync. Never `refs/pull/*`.
22 pub const MIRROR_REFSPECS: [&str; 2] = ["+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"];13 pub const MIRROR_REFSPECS: [&str; 2] = ["+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*"];
23 14
24-/// Most git stderr kept in an error, in bytes.
25 const MAX_STDERR_BYTES: usize = 2 * 1024;15 const MAX_STDERR_BYTES: usize = 2 * 1024;
26 const REDACTED: &str = "[redacted]";16 const REDACTED: &str = "[redacted]";
27 17
28-/// A username and password or token for a remote. The secret is never printed: the `Debug`
29-/// impl redacts it.
30 #[derive(Clone, PartialEq, Eq)]18 #[derive(Clone, PartialEq, Eq)]
31 pub struct RemoteAuth {19 pub struct RemoteAuth {
32 pub username: String,20 pub username: String,
@@ -42,8 +30,6 @@ impl fmt::Debug for RemoteAuth {
42 }30 }
43 }31 }
44 32
45-/// A host and the one address it was checked to resolve to. Git is told to connect to that address
46-/// (`http.curloptResolve`), so the connection cannot be sent somewhere a second DNS lookup returns.
47 #[derive(Clone, Debug, PartialEq, Eq)]33 #[derive(Clone, Debug, PartialEq, Eq)]
48 pub struct PinnedHost {34 pub struct PinnedHost {
49 pub host: String,35 pub host: String,
@@ -52,8 +38,6 @@ pub struct PinnedHost {
52 }38 }
53 39
54 impl PinnedHost {40 impl PinnedHost {
55- /// The `-c` pair for git: `http.curloptResolve=host:port:ip`, with an IPv6 address in brackets.
56- /// The host must be a plain DNS name, so the value cannot smuggle in another option.
57 pub fn config_pair(&self) -> Result<String> {41 pub fn config_pair(&self) -> Result<String> {
58 let plain_host = !self.host.is_empty()42 let plain_host = !self.host.is_empty()
59 && self43 && self
@@ -77,7 +61,6 @@ impl PinnedHost {
77 }61 }
78 62
79 impl RemoteAuth {63 impl RemoteAuth {
80- /// The `Authorization` header value, Basic over `username:secret`.
81 fn header_value(&self) -> String {64 fn header_value(&self) -> String {
82 let mut raw = self.username.as_bytes().to_vec();65 let mut raw = self.username.as_bytes().to_vec();
83 raw.push(b':');66 raw.push(b':');
@@ -86,9 +69,6 @@ impl RemoteAuth {
86 }69 }
87 }70 }
88 71
89-/// Fetches the mirror refs of `url` into the bare repo at `repo`, then points HEAD at the remote's
90-/// default branch when our HEAD's branch is missing. With `pin`, git connects to the pinned
91-/// address. Times out after `timeout`, killing git.
92 pub async fn mirror_fetch(72 pub async fn mirror_fetch(
93 env: &GitEnv,73 env: &GitEnv,
94 repo: &Path,74 repo: &Path,
@@ -102,9 +82,6 @@ pub async fn mirror_fetch(
102 with_timeout(timeout, fetch(env, repo, url, auth, allow_http, pin, false)).await82 with_timeout(timeout, fetch(env, repo, url, auth, allow_http, pin, false)).await
103 }83 }
104 84
105-/// Fetches the mirror refs of a local path over the file transport. This exists so callers' tests
106-/// can import from a bare repo on disk; the web code never calls it, because every user-supplied
107-/// URL goes through [`mirror_fetch`], which refuses `file://`.
108 #[doc(hidden)]85 #[doc(hidden)]
109 pub async fn mirror_fetch_local(86 pub async fn mirror_fetch_local(
110 env: &GitEnv,87 env: &GitEnv,
@@ -115,8 +92,6 @@ pub async fn mirror_fetch_local(
115 with_timeout(timeout, fetch(env, repo, source, None, false, None, true)).await92 with_timeout(timeout, fetch(env, repo, source, None, false, None, true)).await
116 }93 }
117 94
118-/// Pushes the mirror refs of the bare repo at `repo` to `url`, with prune. With `pin`, git connects
119-/// to the pinned address. Times out after `timeout`, killing git.
120 pub async fn mirror_push(95 pub async fn mirror_push(
121 env: &GitEnv,96 env: &GitEnv,
122 repo: &Path,97 repo: &Path,
@@ -130,8 +105,6 @@ pub async fn mirror_push(
130 with_timeout(timeout, push(env, repo, url, auth, allow_http, pin, false)).await105 with_timeout(timeout, push(env, repo, url, auth, allow_http, pin, false)).await
131 }106 }
132 107
133-/// Only https, or http when allowed. No userinfo, whitespace or control characters. Never
134-/// `file://`, `ssh://` or `ext::`.
135 fn check_url(url: &str, allow_http: bool) -> Result<()> {108 fn check_url(url: &str, allow_http: bool) -> Result<()> {
136 let rest = if let Some(rest) = url.strip_prefix("https://") {109 let rest = if let Some(rest) = url.strip_prefix("https://") {
137 rest110 rest
@@ -166,8 +139,6 @@ async fn with_timeout<T>(timeout: Duration, fut: impl Future<Output = Result<T>>
166 }139 }
167 }140 }
168 141
169-/// The git invocation with the safety flags, the optional repo and the optional credentials.
170-/// `local` allows the file transport; only unit tests pass true.
171 fn base_command(142 fn base_command(
172 env: &GitEnv,143 env: &GitEnv,
173 repo: Option<&Path>,144 repo: Option<&Path>,
@@ -234,7 +205,6 @@ async fn fetch(
234 Ok(())205 Ok(())
235 }206 }
236 207
237-/// The `refs/heads/...` target of the remote HEAD symref in `ls-remote --symref` output.
238 fn remote_default_branch(listing: &str) -> Option<String> {208 fn remote_default_branch(listing: &str) -> Option<String> {
239 listing.lines().find_map(|line| {209 listing.lines().find_map(|line| {
240 let (target, name) = line.strip_prefix("ref: ")?.split_once('\t')?;210 let (target, name) = line.strip_prefix("ref: ")?.split_once('\t')?;
@@ -242,8 +212,6 @@ fn remote_default_branch(listing: &str) -> Option<String> {
242 })212 })
243 }213 }
244 214
245-/// Sets HEAD to `default_ref` when HEAD's branch does not exist and `default_ref` does. Best
246-/// effort: failures leave HEAD as it was.
247 async fn point_head_at_default(env: &GitEnv, repo: &Path, default_ref: &str) {215 async fn point_head_at_default(env: &GitEnv, repo: &Path, default_ref: &str) {
248 let current = GitCommand::new(env, "symbolic-ref")216 let current = GitCommand::new(env, "symbolic-ref")
249 .git_dir(repo)217 .git_dir(repo)
@@ -270,7 +238,6 @@ async fn point_head_at_default(env: &GitEnv, repo: &Path, default_ref: &str) {
270 }238 }
271 }239 }
272 240
273-/// True when `refname` is a valid ref name that exists in `repo`.
274 async fn ref_exists(env: &GitEnv, repo: &Path, refname: &str) -> bool {241 async fn ref_exists(env: &GitEnv, repo: &Path, refname: &str) -> bool {
275 let Ok(cmd) = GitCommand::new(env, "show-ref")242 let Ok(cmd) = GitCommand::new(env, "show-ref")
276 .git_dir(repo)243 .git_dir(repo)
@@ -302,7 +269,6 @@ async fn push(
302 Ok(())269 Ok(())
303 }270 }
304 271
305-/// Runs the command and returns stdout. A failure carries git's scrubbed stderr.
306 async fn run_checked(272 async fn run_checked(
307 cmd: GitCommand,273 cmd: GitCommand,
308 what: &str,274 what: &str,
@@ -321,8 +287,6 @@ async fn run_checked(
321 )))287 )))
322 }288 }
323 289
324-/// Removes credentials from text that may reach an error: the secret and its encoded form, any
325-/// `Authorization:` line, and any `user:pass@` in a URL.
326 fn scrub(text: &str, auth: Option<&RemoteAuth>, url: &str) -> String {290 fn scrub(text: &str, auth: Option<&RemoteAuth>, url: &str) -> String {
327 let mut out = text.to_string();291 let mut out = text.to_string();
328 if let Some(auth) = auth {292 if let Some(auth) = auth {
@@ -354,7 +318,6 @@ fn scrub(text: &str, auth: Option<&RemoteAuth>, url: &str) -> String {
354 stripped318 stripped
355 }319 }
356 320
357-/// Replaces `user:pass@` after each `://` with `***@`.
358 fn strip_userinfo(text: &str) -> String {321 fn strip_userinfo(text: &str) -> String {
359 let mut out = String::with_capacity(text.len());322 let mut out = String::with_capacity(text.len());
360 let mut rest = text;323 let mut rest = text;
@@ -378,7 +341,6 @@ fn strip_userinfo(text: &str) -> String {
378 out341 out
379 }342 }
380 343
381-/// At most [`MAX_STDERR_BYTES`], cut at a character boundary.
382 fn truncate(text: &str) -> String {344 fn truncate(text: &str) -> String {
383 if text.len() <= MAX_STDERR_BYTES {345 if text.len() <= MAX_STDERR_BYTES {
384 return text.to_string();346 return text.to_string();
@@ -408,7 +370,6 @@ mod tests {
408 }370 }
409 }371 }
410 372
411- /// Runs plain git against a git dir for test setup.
412 fn plumbing(git_dir: &Path, args: &[&str]) -> String {373 fn plumbing(git_dir: &Path, args: &[&str]) -> String {
413 let out = std::process::Command::new("git")374 let out = std::process::Command::new("git")
414 .arg(format!("--git-dir={}", git_dir.display()))375 .arg(format!("--git-dir={}", git_dir.display()))
@@ -423,7 +384,6 @@ mod tests {
423 String::from_utf8_lossy(&out.stdout).trim().to_string()384 String::from_utf8_lossy(&out.stdout).trim().to_string()
424 }385 }
425 386
426- /// A bare repo whose `main` and tag `v1` point at one empty commit.
427 fn source_repo(dir: &Path) -> std::path::PathBuf {387 fn source_repo(dir: &Path) -> std::path::PathBuf {
428 let git_dir = dir.join("source.git");388 let git_dir = dir.join("source.git");
429 plumbing(dir, &["init", "--bare", "-q", git_dir.to_str().unwrap()]);389 plumbing(dir, &["init", "--bare", "-q", git_dir.to_str().unwrap()]);
@@ -482,7 +442,6 @@ mod tests {
482 assert!(!joined.contains("s3cret"), "{joined}");442 assert!(!joined.contains("s3cret"), "{joined}");
483 assert!(!joined.contains("Authorization"), "{joined}");443 assert!(!joined.contains("Authorization"), "{joined}");
484 assert!(!joined.contains(&STANDARD.encode(b"mirror-bot:s3cret-token-XYZ")));444 assert!(!joined.contains(&STANDARD.encode(b"mirror-bot:s3cret-token-XYZ")));
485- // The header travels in the environment instead.
486 let env_value = std_cmd445 let env_value = std_cmd
487 .get_envs()446 .get_envs()
488 .find(|(k, _)| *k == "GIT_CONFIG_VALUE_0")447 .find(|(k, _)| *k == "GIT_CONFIG_VALUE_0")
@@ -540,8 +499,6 @@ mod tests {
540 let env = env(dir.path());499 let env = env(dir.path());
541 let timeout = Duration::from_secs(60);500 let timeout = Duration::from_secs(60);
542 501
543- // Pull: fetch the source into an empty bare repo, through the local transport that
544- // only unit tests may use.
545 let pulled = dir.path().join("pulled.git");502 let pulled = dir.path().join("pulled.git");
546 plumbing(503 plumbing(
547 dir.path(),504 dir.path(),
@@ -558,7 +515,6 @@ mod tests {
558 "refs/heads/main"515 "refs/heads/main"
559 );516 );
560 517
561- // A branch that the remote no longer has is pruned by the next fetch.
562 let head = plumbing(&source, &["rev-parse", "refs/heads/main"]);518 let head = plumbing(&source, &["rev-parse", "refs/heads/main"]);
563 plumbing(&pulled, &["update-ref", "refs/heads/gone", &head]);519 plumbing(&pulled, &["update-ref", "refs/heads/gone", &head]);
564 plumbing(&source, &["update-ref", "refs/heads/new", &head]);520 plumbing(&source, &["update-ref", "refs/heads/new", &head]);
@@ -569,7 +525,6 @@ mod tests {
569 assert!(fetched.contains("refs/heads/new"), "{fetched}");525 assert!(fetched.contains("refs/heads/new"), "{fetched}");
570 assert!(!fetched.contains("refs/heads/gone"), "{fetched}");526 assert!(!fetched.contains("refs/heads/gone"), "{fetched}");
571 527
572- // Push: mirror our refs to an empty bare remote, then prune a stale branch there.
573 let remote = dir.path().join("remote.git");528 let remote = dir.path().join("remote.git");
574 plumbing(529 plumbing(
575 dir.path(),530 dir.path(),
@@ -592,7 +547,6 @@ mod tests {
592 assert!(pushed.contains("refs/tags/v1"), "{pushed}");547 assert!(pushed.contains("refs/tags/v1"), "{pushed}");
593 assert!(!pushed.contains("refs/heads/stale"), "{pushed}");548 assert!(!pushed.contains("refs/heads/stale"), "{pushed}");
594 549
595- // The public entry points reject the file transport outright.
596 assert!(550 assert!(
597 mirror_fetch(551 mirror_fetch(
598 &env,552 &env,
@@ -631,7 +585,6 @@ mod tests {
631 &["init", "--bare", "-q", pulled.to_str().unwrap()],585 &["init", "--bare", "-q", pulled.to_str().unwrap()],
632 );586 );
633 let a = auth();587 let a = auth();
634- // Port 9 on loopback refuses the connection, so git fails with its own error text.
635 let url = "https://127.0.0.1:9/x.git";588 let url = "https://127.0.0.1:9/x.git";
636 let err = mirror_fetch(589 let err = mirror_fetch(
637 &env,590 &env,
@@ -729,8 +682,6 @@ mod tests {
729 dir.path(),682 dir.path(),
730 &["init", "--bare", "-q", pulled.to_str().expect("utf8 path")],683 &["init", "--bare", "-q", pulled.to_str().expect("utf8 path")],
731 );684 );
732- // The host never resolves, so only the pin can get git past name lookup. Nothing listens
733- // on loopback port 443, so the run fails at connect, not at resolve.
734 let err = mirror_fetch(685 let err = mirror_fetch(
735 &env,686 &env,
736 &pulled,687 &pulled,
crates/forge-git/src/pktline.rsmodified+0 -6
@@ -1,12 +1,7 @@
1-//! pkt-line framing for smart HTTP.
2-
3 use crate::service::GitService;1 use crate::service::GitService;
4 2
5-/// The flush packet `0000`.
6 pub const FLUSH_PKT: &[u8] = b"0000";3 pub const FLUSH_PKT: &[u8] = b"0000";
7 4
8-/// Frames `data` as a pkt-line (4 hex length digits, including the 4 length bytes).
9-/// The payload must be at most 65516 bytes; callers pass short protocol strings.
10 pub fn pkt_line(data: &str) -> Vec<u8> {5 pub fn pkt_line(data: &str) -> Vec<u8> {
11 let len = data.len() + 4;6 let len = data.len() + 4;
12 debug_assert!(len <= 0xffff, "pkt-line payload too long");7 debug_assert!(len <= 0xffff, "pkt-line payload too long");
@@ -15,7 +10,6 @@ pub fn pkt_line(data: &str) -> Vec<u8> {
15 out10 out
16 }11 }
17 12
18-/// The smart-HTTP advertisement preamble: `# service=git-<svc>` as a pkt-line, then a flush.
19 pub fn service_advertisement_header(svc: GitService) -> Vec<u8> {13 pub fn service_advertisement_header(svc: GitService) -> Vec<u8> {
20 let mut out = pkt_line(&format!("# service={}\n", svc.name()));14 let mut out = pkt_line(&format!("# service={}\n", svc.name()));
21 out.extend_from_slice(FLUSH_PKT);15 out.extend_from_slice(FLUSH_PKT);
crates/forge-git/src/repo.rsmodified+0 -40
@@ -1,5 +1,3 @@
1-//! Bare repository layout and basic queries.
2-
3 use std::path::{Path, PathBuf};1 use std::path::{Path, PathBuf};
4 2
5 use forge_core::time::unix_now;3 use forge_core::time::unix_now;
@@ -7,11 +5,8 @@ use forge_core::time::unix_now;
7 use crate::command::{GitCommand, GitEnv};5 use crate::command::{GitCommand, GitEnv};
8 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
9 7
10-/// Crockford base32 alphabet used by ULIDs, lowercase.
11 const ULID_ALPHABET: &[u8] = b"0123456789abcdefghjkmnpqrstvwxyz";8 const ULID_ALPHABET: &[u8] = b"0123456789abcdefghjkmnpqrstvwxyz";
12 9
13-/// `data_dir/repos/<id[0..2]>/<id[2..4]>/<id>.git`, with the ULID lowercased.
14-/// Fails with `Error::InvalidInput` unless `repo_id` is a 26-character ULID.
15 pub fn repo_path(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {10 pub fn repo_path(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {
16 let id = repo_id.to_ascii_lowercase();11 let id = repo_id.to_ascii_lowercase();
17 if id.len() != 26 || !id.bytes().all(|b| ULID_ALPHABET.contains(&b)) {12 if id.len() != 26 || !id.bytes().all(|b| ULID_ALPHABET.contains(&b)) {
@@ -24,38 +19,27 @@ pub fn repo_path(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {
24 .join(format!("{id}.git")))19 .join(format!("{id}.git")))
25 }20 }
26 21
27-/// `data_dir/repos/<id[0..2]>/<id[2..4]>/<id>.wiki.git`: the repo's wiki, a second bare repo next
28-/// to the main one. Same ULID check as [`repo_path`].
29 pub fn wiki_path(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {22 pub fn wiki_path(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {
30 let main = repo_path(data_dir, repo_id)?;23 let main = repo_path(data_dir, repo_id)?;
31 Ok(main.with_extension("").with_extension("wiki.git"))24 Ok(main.with_extension("").with_extension("wiki.git"))
32 }25 }
33 26
34-/// Directory under `data_dir` that holds deleted repos until they are purged.
35 pub const TRASH_DIR: &str = "trash";27 pub const TRASH_DIR: &str = "trash";
36 28
37-/// One directory in the trash, named `<repo_id>-<unix_ts>.git`. It is a plain bare repo.
38 #[derive(Debug, Clone, PartialEq, Eq)]29 #[derive(Debug, Clone, PartialEq, Eq)]
39 pub struct TrashEntry {30 pub struct TrashEntry {
40 pub path: PathBuf,31 pub path: PathBuf,
41 pub repo_id: String,32 pub repo_id: String,
42- /// Unix seconds at which the repo was moved to trash.
43 pub deleted_at: u64,33 pub deleted_at: u64,
44- /// True for a wiki (`<id>.wiki-<ts>.git`), false for the code repo (`<id>-<ts>.git`).
45 pub wiki: bool,34 pub wiki: bool,
46 }35 }
47 36
48-/// Renames the bare repo for `repo_id` into `data_dir/trash/<id>-<unix_ts>.git` and returns the
49-/// new path. A rename stays on one filesystem, so nothing is copied and nothing is deleted.
50-/// Fails without touching anything when the repo directory is missing or the target exists.
51 pub async fn move_to_trash(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {37 pub async fn move_to_trash(data_dir: &Path, repo_id: &str) -> Result<PathBuf> {
52 let src = repo_path(data_dir, repo_id)?;38 let src = repo_path(data_dir, repo_id)?;
53 let name = format!("{}-{}.git", repo_id.to_ascii_lowercase(), unix_now());39 let name = format!("{}-{}.git", repo_id.to_ascii_lowercase(), unix_now());
54 trash_dir(data_dir, &src, &name).await40 trash_dir(data_dir, &src, &name).await
55 }41 }
56 42
57-/// Renames the wiki repo of `repo_id`, if it has one, into `trash/<id>.wiki-<unix_ts>.git`.
58-/// Returns `None` when the repo has no wiki, so nothing is touched.
59 pub async fn move_wiki_to_trash(data_dir: &Path, repo_id: &str) -> Result<Option<PathBuf>> {43 pub async fn move_wiki_to_trash(data_dir: &Path, repo_id: &str) -> Result<Option<PathBuf>> {
60 let src = wiki_path(data_dir, repo_id)?;44 let src = wiki_path(data_dir, repo_id)?;
61 if !tokio::fs::try_exists(&src).await? {45 if !tokio::fs::try_exists(&src).await? {
@@ -65,7 +49,6 @@ pub async fn move_wiki_to_trash(data_dir: &Path, repo_id: &str) -> Result<Option
65 trash_dir(data_dir, &src, &name).await.map(Some)49 trash_dir(data_dir, &src, &name).await.map(Some)
66 }50 }
67 51
68-/// Moves `src` to `trash/<name>`. Fails when `src` is missing or the target already exists.
69 async fn trash_dir(data_dir: &Path, src: &Path, name: &str) -> Result<PathBuf> {52 async fn trash_dir(data_dir: &Path, src: &Path, name: &str) -> Result<PathBuf> {
70 if !tokio::fs::try_exists(src).await? {53 if !tokio::fs::try_exists(src).await? {
71 return Err(Error::Io(std::io::Error::new(54 return Err(Error::Io(std::io::Error::new(
@@ -86,9 +69,6 @@ async fn trash_dir(data_dir: &Path, src: &Path, name: &str) -> Result<PathBuf> {
86 Ok(dest)69 Ok(dest)
87 }70 }
88 71
89-/// True when the bare repo directory for `repo_id` is confirmed absent (`NotFound` from
90-/// `symlink_metadata`). Any other error, such as a permission failure, is returned so that callers
91-/// can abort instead of treating the directory as missing.
92 pub fn repo_dir_missing(data_dir: &Path, repo_id: &str) -> Result<bool> {72 pub fn repo_dir_missing(data_dir: &Path, repo_id: &str) -> Result<bool> {
93 let src = repo_path(data_dir, repo_id)?;73 let src = repo_path(data_dir, repo_id)?;
94 match std::fs::symlink_metadata(&src) {74 match std::fs::symlink_metadata(&src) {
@@ -98,14 +78,11 @@ pub fn repo_dir_missing(data_dir: &Path, repo_id: &str) -> Result<bool> {
98 }78 }
99 }79 }
100 80
101-/// Moves a trashed repo back to its place under `data_dir/repos`. Used to undo `move_to_trash`
102-/// when the database delete fails. Refuses to overwrite an existing repo directory.
103 pub async fn restore_from_trash(data_dir: &Path, trashed: &Path, repo_id: &str) -> Result<()> {81 pub async fn restore_from_trash(data_dir: &Path, trashed: &Path, repo_id: &str) -> Result<()> {
104 let dest = repo_path(data_dir, repo_id)?;82 let dest = repo_path(data_dir, repo_id)?;
105 restore_to(&dest, trashed).await83 restore_to(&dest, trashed).await
106 }84 }
107 85
108-/// Moves a trashed wiki back to its place. Used to undo `move_wiki_to_trash`.
109 pub async fn restore_wiki_from_trash(data_dir: &Path, trashed: &Path, repo_id: &str) -> Result<()> {86 pub async fn restore_wiki_from_trash(data_dir: &Path, trashed: &Path, repo_id: &str) -> Result<()> {
110 let dest = wiki_path(data_dir, repo_id)?;87 let dest = wiki_path(data_dir, repo_id)?;
111 restore_to(&dest, trashed).await88 restore_to(&dest, trashed).await
@@ -125,7 +102,6 @@ async fn restore_to(dest: &Path, trashed: &Path) -> Result<()> {
125 Ok(())102 Ok(())
126 }103 }
127 104
128-/// Lists trash entries, oldest first. Directories whose names do not parse are skipped.
129 pub fn list_trash(data_dir: &Path) -> Result<Vec<TrashEntry>> {105 pub fn list_trash(data_dir: &Path) -> Result<Vec<TrashEntry>> {
130 let dir = data_dir.join(TRASH_DIR);106 let dir = data_dir.join(TRASH_DIR);
131 if !dir.is_dir() {107 if !dir.is_dir() {
@@ -166,8 +142,6 @@ pub fn list_trash(data_dir: &Path) -> Result<Vec<TrashEntry>> {
166 Ok(entries)142 Ok(entries)
167 }143 }
168 144
169-/// Permanently removes trash entries deleted at least `older_than_secs` before `now`.
170-/// Returns the removed paths. Only entries that `list_trash` recognises are removed.
171 pub fn purge_trash(data_dir: &Path, older_than_secs: u64, now: u64) -> Result<Vec<PathBuf>> {145 pub fn purge_trash(data_dir: &Path, older_than_secs: u64, now: u64) -> Result<Vec<PathBuf>> {
172 let mut removed = Vec::new();146 let mut removed = Vec::new();
173 for entry in list_trash(data_dir)? {147 for entry in list_trash(data_dir)? {
@@ -179,7 +153,6 @@ pub fn purge_trash(data_dir: &Path, older_than_secs: u64, now: u64) -> Result<Ve
179 Ok(removed)153 Ok(removed)
180 }154 }
181 155
182-/// Checks a branch name with `git check-ref-format --branch`.
183 pub(crate) async fn check_branch(env: &GitEnv, name: &str) -> Result<()> {156 pub(crate) async fn check_branch(env: &GitEnv, name: &str) -> Result<()> {
184 let cmd = GitCommand::new(env, "check-ref-format")157 let cmd = GitCommand::new(env, "check-ref-format")
185 .arg("--branch")158 .arg("--branch")
@@ -193,7 +166,6 @@ pub(crate) async fn check_branch(env: &GitEnv, name: &str) -> Result<()> {
193 }166 }
194 }167 }
195 168
196-/// Runs `git init --bare` at `path` with the given default branch.
197 pub async fn init_bare(env: &GitEnv, path: &Path, default_branch: &str) -> Result<()> {169 pub async fn init_bare(env: &GitEnv, path: &Path, default_branch: &str) -> Result<()> {
198 check_branch(env, default_branch).await?;170 check_branch(env, default_branch).await?;
199 let path_str = path171 let path_str = path
@@ -210,7 +182,6 @@ pub async fn init_bare(env: &GitEnv, path: &Path, default_branch: &str) -> Resul
210 .await182 .await
211 }183 }
212 184
213-/// Lists branch names in the repo at `path`.
214 pub async fn list_branches(env: &GitEnv, path: &Path) -> Result<Vec<String>> {185 pub async fn list_branches(env: &GitEnv, path: &Path) -> Result<Vec<String>> {
215 let out = GitCommand::new(env, "for-each-ref")186 let out = GitCommand::new(env, "for-each-ref")
216 .git_dir(path)187 .git_dir(path)
@@ -225,10 +196,6 @@ pub async fn list_branches(env: &GitEnv, path: &Path) -> Result<Vec<String>> {
225 .collect())196 .collect())
226 }197 }
227 198
228-/// Copies `src` (a bare repo) to the new bare repo `dst` for a fork. Objects are hardlinked
229-/// (`--local`), which is safe because objects are immutable. Only `refs/heads/*` and `refs/tags/*`
230-/// survive; anything else (such as `refs/pull/*`) is deleted, and an `origin` remote is removed if
231-/// the clone added one. `dst` must not exist. On failure after the clone starts, `dst` is removed.
232 pub async fn fork_bare(env: &GitEnv, src: &Path, dst: &Path) -> Result<()> {199 pub async fn fork_bare(env: &GitEnv, src: &Path, dst: &Path) -> Result<()> {
233 if tokio::fs::try_exists(dst).await? {200 if tokio::fs::try_exists(dst).await? {
234 return Err(Error::InvalidInput(format!(201 return Err(Error::InvalidInput(format!(
@@ -245,7 +212,6 @@ pub async fn fork_bare(env: &GitEnv, src: &Path, dst: &Path) -> Result<()> {
245 if let Some(parent) = dst.parent() {212 if let Some(parent) = dst.parent() {
246 tokio::fs::create_dir_all(parent).await?;213 tokio::fs::create_dir_all(parent).await?;
247 }214 }
248- // `src` is a bare repo from repo_path(), so the local transport is allowed for this call only.
249 GitCommand::new(env, "clone")215 GitCommand::new(env, "clone")
250 .allow_local_transport()216 .allow_local_transport()
251 .arg("--bare")217 .arg("--bare")
@@ -255,14 +221,12 @@ pub async fn fork_bare(env: &GitEnv, src: &Path, dst: &Path) -> Result<()> {
255 .status()221 .status()
256 .await?;222 .await?;
257 if let Err(e) = prune_fork(env, dst).await {223 if let Err(e) = prune_fork(env, dst).await {
258- // The clone created `dst` (it did not exist before), so removing it leaves nothing behind.
259 let _ = tokio::fs::remove_dir_all(dst).await;224 let _ = tokio::fs::remove_dir_all(dst).await;
260 return Err(e);225 return Err(e);
261 }226 }
262 Ok(())227 Ok(())
263 }228 }
264 229
265-/// The clone-after steps of `fork_bare`: keep only branches and tags, and drop a clone-added origin.
266 async fn prune_fork(env: &GitEnv, dst: &Path) -> Result<()> {230 async fn prune_fork(env: &GitEnv, dst: &Path) -> Result<()> {
267 let out = GitCommand::new(env, "for-each-ref")231 let out = GitCommand::new(env, "for-each-ref")
268 .git_dir(dst)232 .git_dir(dst)
@@ -362,7 +326,6 @@ mod tests {
362 );326 );
363 assert_eq!(listed[0].repo_id, ID);327 assert_eq!(listed[0].repo_id, ID);
364 328
365- // Cutoff: anything deleted at or before now - 3000 goes.
366 let removed = purge_trash(dir.path(), 3000, 5000).unwrap();329 let removed = purge_trash(dir.path(), 3000, 5000).unwrap();
367 assert_eq!(removed, vec![trash.join(format!("{ID}-1000.git"))]);330 assert_eq!(removed, vec![trash.join(format!("{ID}-1000.git"))]);
368 assert!(!trash.join(format!("{ID}-1000.git")).exists());331 assert!(!trash.join(format!("{ID}-1000.git")).exists());
@@ -370,7 +333,6 @@ mod tests {
370 assert!(trash.join("not-a-trash-entry").exists());333 assert!(trash.join("not-a-trash-entry").exists());
371 }334 }
372 335
373- /// Runs `git` in `cwd` with a fixed identity and returns stdout. Panics on failure (tests only).
374 fn git_in(cwd: &Path, args: &[&str]) -> String {336 fn git_in(cwd: &Path, args: &[&str]) -> String {
375 let out = std::process::Command::new("/usr/bin/git")337 let out = std::process::Command::new("/usr/bin/git")
376 .current_dir(cwd)338 .current_dir(cwd)
@@ -396,7 +358,6 @@ mod tests {
396 #[tokio::test]358 #[tokio::test]
397 async fn fork_bare_keeps_only_branches_and_tags() {359 async fn fork_bare_keeps_only_branches_and_tags() {
398 let dir = tempfile::tempdir().unwrap();360 let dir = tempfile::tempdir().unwrap();
399- // The real managed gitconfig, so the test sees `protocol.file.allow = never`.
400 crate::setup::write_managed_gitconfig(dir.path()).unwrap();361 crate::setup::write_managed_gitconfig(dir.path()).unwrap();
401 let env = GitEnv {362 let env = GitEnv {
402 git_bin: "/usr/bin/git".into(),363 git_bin: "/usr/bin/git".into(),
@@ -414,7 +375,6 @@ mod tests {
414 git_in(&work, &["tag", "v1"]);375 git_in(&work, &["tag", "v1"]);
415 let src_str = src.to_str().unwrap();376 let src_str = src.to_str().unwrap();
416 git_in(&work, &["push", "-q", src_str, "main", "v1"]);377 git_in(&work, &["push", "-q", src_str, "main", "v1"]);
417- // A pull ref that a fork must not inherit.
418 git_in(&src, &["update-ref", "refs/pull/1/head", "refs/heads/main"]);378 git_in(&src, &["update-ref", "refs/pull/1/head", "refs/heads/main"]);
419 379
420 let dst = repo_path(dir.path(), ID).unwrap();380 let dst = repo_path(dir.path(), ID).unwrap();
crates/forge-git/src/search.rsmodified+0 -29
@@ -1,7 +1,3 @@
1-//! Per-repo code search with `git grep` at one commit. No index: each query runs git once,
2-//! streams its output, and stops (killing git) after `max_matches` hits. The commit is a validated
3-//! full object id; the query goes after `-e`; the optional glob goes after `--`.
4-
5 use std::path::Path;1 use std::path::Path;
6 use std::process::Stdio;2 use std::process::Stdio;
7 use std::time::Duration;3 use std::time::Duration;
@@ -12,22 +8,15 @@ use crate::command::GitEnv;
12 use crate::error::{Error, Result};8 use crate::error::{Error, Result};
13 use crate::history::{git, read_pipe_head, validate_oid};9 use crate::history::{git, read_pipe_head, validate_oid};
14 10
15-/// Longest accepted query, in bytes.
16 pub const MAX_QUERY_BYTES: usize = 200;11 pub const MAX_QUERY_BYTES: usize = 200;
17-/// Longest accepted path glob, in bytes.
18 const MAX_GLOB_BYTES: usize = 512;12 const MAX_GLOB_BYTES: usize = 512;
19-/// Longest line text kept in a hit, in characters.
20 const MAX_LINE_CHARS: usize = 500;13 const MAX_LINE_CHARS: usize = 500;
21-/// Bytes kept of one `git grep` output line. Up to 4 bytes per character, so this holds the
22-/// header (commit, path, line number) and `MAX_LINE_CHARS` of text; the rest is dropped unread.
23 const MAX_RECORD_BYTES: usize = 4 * MAX_LINE_CHARS + 4096;14 const MAX_RECORD_BYTES: usize = 4 * MAX_LINE_CHARS + 4096;
24 15
25 #[derive(Debug, Clone, PartialEq, Eq)]16 #[derive(Debug, Clone, PartialEq, Eq)]
26 pub struct GrepOptions {17 pub struct GrepOptions {
27- /// Match the query as plain text (`-F`) rather than as an extended regex (`-E`).
28 pub fixed: bool,18 pub fixed: bool,
29 pub ignore_case: bool,19 pub ignore_case: bool,
30- /// Limits the search to paths matching this git pathspec glob.
31 pub path_glob: Option<String>,20 pub path_glob: Option<String>,
32 pub max_matches: usize,21 pub max_matches: usize,
33 pub timeout: Duration,22 pub timeout: Duration,
@@ -49,14 +38,12 @@ impl Default for GrepOptions {
49 pub struct GrepHit {38 pub struct GrepHit {
50 pub path: String,39 pub path: String,
51 pub line_no: u32,40 pub line_no: u32,
52- /// The matching line, cut to 500 characters.
53 pub line: String,41 pub line: String,
54 }42 }
55 43
56 #[derive(Debug, Clone, PartialEq, Eq)]44 #[derive(Debug, Clone, PartialEq, Eq)]
57 pub struct GrepResult {45 pub struct GrepResult {
58 pub hits: Vec<GrepHit>,46 pub hits: Vec<GrepHit>,
59- /// True when more matches existed than `max_matches`.
60 pub truncated: bool,47 pub truncated: bool,
61 }48 }
62 49
@@ -91,7 +78,6 @@ fn validate_glob(glob: &str) -> Result<()> {
91 Ok(())78 Ok(())
92 }79 }
93 80
94-/// Parses one `--null` record, `<commit>:<path>\0<line>\0<text>`, without its trailing newline.
95 fn parse_record(record: &[u8], commit: &str) -> Option<GrepHit> {81 fn parse_record(record: &[u8], commit: &str) -> Option<GrepHit> {
96 let mut parts = record.splitn(3, |&b| b == 0);82 let mut parts = record.splitn(3, |&b| b == 0);
97 let header = parts.next()?;83 let header = parts.next()?;
@@ -110,9 +96,6 @@ fn parse_record(record: &[u8], commit: &str) -> Option<GrepHit> {
110 })96 })
111 }97 }
112 98
113-/// Reads one line into `buf`, without its `\n`, keeping at most `keep` bytes of it. The rest of
114-/// the line is consumed and dropped, so a huge line does not allocate its whole size. Returns
115-/// false at end of input.
116 async fn read_line_capped<R: AsyncBufRead + Unpin>(99 async fn read_line_capped<R: AsyncBufRead + Unpin>(
117 reader: &mut R,100 reader: &mut R,
118 buf: &mut Vec<u8>,101 buf: &mut Vec<u8>,
@@ -138,7 +121,6 @@ async fn read_line_capped<R: AsyncBufRead + Unpin>(
138 }121 }
139 }122 }
140 123
141-/// Searches the tree of `commit` for `query`. Exit code 1 from git (no match) is an empty result.
142 pub async fn grep(124 pub async fn grep(
143 env: &GitEnv,125 env: &GitEnv,
144 repo: &Path,126 repo: &Path,
@@ -214,7 +196,6 @@ pub async fn grep(
214 Some(task) => task.await.unwrap_or_default(),196 Some(task) => task.await.unwrap_or_default(),
215 None => Vec::new(),197 None => Vec::new(),
216 };198 };
217- // Git exits 1 when nothing matched. A killed child (truncated) has no meaningful code.
218 if !truncated && !status.success() && status.code() != Some(1) {199 if !truncated && !status.success() && status.code() != Some(1) {
219 return Err(Error::Failed(format!(200 return Err(Error::Failed(format!(
220 "git grep exited with {status}: {}",201 "git grep exited with {status}: {}",
@@ -254,7 +235,6 @@ mod tests {
254 assert!(status.success(), "git {args:?} failed");235 assert!(status.success(), "git {args:?} failed");
255 }236 }
256 237
257- /// A repo with `src/main.rs`, `docs/Guide.md` and `src/lib.rs`. Returns (git dir, commit oid).
258 fn fixture(dir: &Path) -> (std::path::PathBuf, String) {238 fn fixture(dir: &Path) -> (std::path::PathBuf, String) {
259 let work = dir.join("work");239 let work = dir.join("work");
260 std::fs::create_dir_all(work.join("src")).unwrap();240 std::fs::create_dir_all(work.join("src")).unwrap();
@@ -278,15 +258,12 @@ mod tests {
278 (work.join(".git"), oid)258 (work.join(".git"), oid)
279 }259 }
280 260
281- /// Fixed and regex modes, case folding, path globs, the match cap and the
282- /// empty result share one fixture, so the repo is built once.
283 #[tokio::test]261 #[tokio::test]
284 async fn grep_modes_and_limits_on_one_fixture() {262 async fn grep_modes_and_limits_on_one_fixture() {
285 let dir = tempfile::tempdir().unwrap();263 let dir = tempfile::tempdir().unwrap();
286 let (repo, oid) = fixture(dir.path());264 let (repo, oid) = fixture(dir.path());
287 let env = env(dir.path());265 let env = env(dir.path());
288 266
289- // Fixed mode: the dot is literal, so only `a.b` matches.
290 let res = grep(&env, &repo, &oid, "a.b", GrepOptions::default())267 let res = grep(&env, &repo, &oid, "a.b", GrepOptions::default())
291 .await268 .await
292 .unwrap();269 .unwrap();
@@ -296,7 +273,6 @@ mod tests {
296 assert_eq!(res.hits[0].line, "let a.b = 1;", "fixed");273 assert_eq!(res.hits[0].line, "let a.b = 1;", "fixed");
297 assert!(!res.truncated, "fixed");274 assert!(!res.truncated, "fixed");
298 275
299- // Case-sensitive versus ignore-case.
300 let sensitive = grep(&env, &repo, &oid, "hello", GrepOptions::default())276 let sensitive = grep(&env, &repo, &oid, "hello", GrepOptions::default())
301 .await277 .await
302 .unwrap();278 .unwrap();
@@ -312,7 +288,6 @@ mod tests {
312 let insensitive = grep(&env, &repo, &oid, "HELLO", opts).await.unwrap();288 let insensitive = grep(&env, &repo, &oid, "HELLO", opts).await.unwrap();
313 assert_eq!(insensitive.hits.len(), 3, "ignore case");289 assert_eq!(insensitive.hits.len(), 3, "ignore case");
314 290
315- // Regex mode.
316 let regex = GrepOptions {291 let regex = GrepOptions {
317 fixed: false,292 fixed: false,
318 ..GrepOptions::default()293 ..GrepOptions::default()
@@ -323,7 +298,6 @@ mod tests {
323 assert_eq!(res.hits.len(), 1, "regex");298 assert_eq!(res.hits.len(), 1, "regex");
324 assert_eq!(res.hits[0].path, "src/lib.rs", "regex");299 assert_eq!(res.hits[0].path, "src/lib.rs", "regex");
325 300
326- // Path glob limits the search.
327 let opts = GrepOptions {301 let opts = GrepOptions {
328 path_glob: Some("*.md".into()),302 path_glob: Some("*.md".into()),
329 ..GrepOptions::default()303 ..GrepOptions::default()
@@ -332,7 +306,6 @@ mod tests {
332 assert_eq!(res.hits.len(), 1, "path glob");306 assert_eq!(res.hits.len(), 1, "path glob");
333 assert_eq!(res.hits[0].path, "docs/Guide.md", "path glob");307 assert_eq!(res.hits[0].path, "docs/Guide.md", "path glob");
334 308
335- // The match cap truncates.
336 let opts = GrepOptions {309 let opts = GrepOptions {
337 ignore_case: true,310 ignore_case: true,
338 max_matches: 2,311 max_matches: 2,
@@ -342,7 +315,6 @@ mod tests {
342 assert_eq!(res.hits.len(), 2, "max matches");315 assert_eq!(res.hits.len(), 2, "max matches");
343 assert!(res.truncated, "max matches");316 assert!(res.truncated, "max matches");
344 317
345- // No match is an empty result, not an error.
346 let res = grep(&env, &repo, &oid, "zzz-not-here", GrepOptions::default())318 let res = grep(&env, &repo, &oid, "zzz-not-here", GrepOptions::default())
347 .await319 .await
348 .unwrap();320 .unwrap();
@@ -405,7 +377,6 @@ mod tests {
405 .await377 .await
406 .is_err()378 .is_err()
407 );379 );
408- // A bad regex is a git failure, not an empty result.
409 let bad_regex = GrepOptions {380 let bad_regex = GrepOptions {
410 fixed: false,381 fixed: false,
411 ..GrepOptions::default()382 ..GrepOptions::default()
crates/forge-git/src/seed.rsmodified+0 -9
@@ -1,7 +1,3 @@
1-//! The first commit of a new repo, for the README and license files the create form can add. It
2-//! is written with the same plumbing as a wiki page (see [`crate::wiki`]): `hash-object`, a
3-//! temporary index, `write-tree`, `commit-tree`, and a compare-and-swap `update-ref`.
4-
5 use std::path::Path;1 use std::path::Path;
6 2
7 use crate::command::{GitCommand, GitEnv};3 use crate::command::{GitCommand, GitEnv};
@@ -10,9 +6,6 @@ use crate::history::zero_oid;
10 use crate::repo::check_branch;6 use crate::repo::check_branch;
11 use crate::wiki::temp_index;7 use crate::wiki::temp_index;
12 8
13-/// Commits `files` (path and bytes, all at the top level) as the only commit on `branch` of the
14-/// bare repo at `repo`, and returns it. The branch must not exist yet: the ref is moved from the
15-/// zero oid, so an existing branch is an error and nothing is written to it.
16 pub async fn initial_commit(9 pub async fn initial_commit(
17 env: &GitEnv,10 env: &GitEnv,
18 repo: &Path,11 repo: &Path,
@@ -35,7 +28,6 @@ pub async fn initial_commit(
35 message,28 message,
36 )29 )
37 .await;30 .await;
38- // The index is scratch space. A leftover file is harmless, but do not keep it.
39 let _ = tokio::fs::remove_file(&index).await;31 let _ = tokio::fs::remove_file(&index).await;
40 result32 result
41 }33 }
@@ -91,7 +83,6 @@ async fn write_commit(
91 let oid = commit.output_stdin(message.as_bytes()).await?;83 let oid = commit.output_stdin(message.as_bytes()).await?;
92 let oid = String::from_utf8_lossy(&oid).trim().to_owned();84 let oid = String::from_utf8_lossy(&oid).trim().to_owned();
93 85
94- // The zero oid makes this a create: it fails if the branch already has a commit.
95 GitCommand::new(env, "update-ref")86 GitCommand::new(env, "update-ref")
96 .git_dir(repo)87 .git_dir(repo)
97 .arg("-m")88 .arg("-m")
crates/forge-git/src/service.rsmodified+0 -11
@@ -1,5 +1,3 @@
1-//! Smart-HTTP and SSH service selection and command construction.
2-
3 use std::path::Path;1 use std::path::Path;
4 2
5 use crate::command::{GitCommand, GitEnv};3 use crate::command::{GitCommand, GitEnv};
@@ -11,7 +9,6 @@ pub enum GitService {
11 }9 }
12 10
13 impl GitService {11 impl GitService {
14- /// Accepts `git-upload-pack` or `git-receive-pack`.
15 pub fn from_name(s: &str) -> Option<Self> {12 pub fn from_name(s: &str) -> Option<Self> {
16 match s {13 match s {
17 "git-upload-pack" => Some(GitService::UploadPack),14 "git-upload-pack" => Some(GitService::UploadPack),
@@ -20,7 +17,6 @@ impl GitService {
20 }17 }
21 }18 }
22 19
23- /// `git-upload-pack` or `git-receive-pack`.
24 pub fn name(&self) -> &'static str {20 pub fn name(&self) -> &'static str {
25 match self {21 match self {
26 GitService::UploadPack => "git-upload-pack",22 GitService::UploadPack => "git-upload-pack",
@@ -28,7 +24,6 @@ impl GitService {
28 }24 }
29 }25 }
30 26
31- /// The `git` subcommand, without the `git-` prefix.
32 fn subcommand(&self) -> &'static str {27 fn subcommand(&self) -> &'static str {
33 match self {28 match self {
34 GitService::UploadPack => "upload-pack",29 GitService::UploadPack => "upload-pack",
@@ -37,12 +32,8 @@ impl GitService {
37 }32 }
38 }33 }
39 34
40-/// The largest pack one push may send (2 GiB, like the LFS object limit). Larger files belong in LFS.
41 const MAX_PUSH_CONFIG: &str = "receive.maxInputSize=2g";35 const MAX_PUSH_CONFIG: &str = "receive.maxInputSize=2g";
42 36
43-/// Builds `git <upload-pack|receive-pack> [--stateless-rpc] [--advertise-refs] -- <repo>`.
44-/// `git_protocol` is passed as `GIT_PROTOCOL`. For SSH, pass `stateless_rpc=false` and
45-/// `advertise_refs=false` to get no flags.
46 pub fn service_command(37 pub fn service_command(
47 env: &GitEnv,38 env: &GitEnv,
48 svc: GitService,39 svc: GitService,
@@ -53,8 +44,6 @@ pub fn service_command(
53 ) -> GitCommand {44 ) -> GitCommand {
54 let mut cmd = GitCommand::new(env, svc.subcommand());45 let mut cmd = GitCommand::new(env, svc.subcommand());
55 if svc == GitService::ReceivePack {46 if svc == GitService::ReceivePack {
56- // One push's pack may be at most this big; git refuses the rest and stops reading, so a
57- // client (or a small gzip body that inflates) cannot stream into the disk without end.
58 cmd = cmd.config(MAX_PUSH_CONFIG);47 cmd = cmd.config(MAX_PUSH_CONFIG);
59 }48 }
60 if stateless_rpc {49 if stateless_rpc {
crates/forge-git/src/setup.rsmodified+0 -10
@@ -1,5 +1,3 @@
1-//! Managed gitconfig and hook shims, written into the data dir at boot.
2-
3 use std::fs::{self, File};1 use std::fs::{self, File};
4 use std::io::Write;2 use std::io::Write;
5 use std::os::unix::fs::PermissionsExt;3 use std::os::unix::fs::PermissionsExt;
@@ -7,7 +5,6 @@ use std::path::Path;
7 5
8 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
9 7
10-/// Quotes a value for a git config file. Control characters are rejected.
11 fn quote_config_value(v: &str) -> Result<String> {8 fn quote_config_value(v: &str) -> Result<String> {
12 if v.chars().any(char::is_control) {9 if v.chars().any(char::is_control) {
13 return Err(Error::InvalidInput(format!(10 return Err(Error::InvalidInput(format!(
@@ -20,7 +17,6 @@ fn quote_config_value(v: &str) -> Result<String> {
20 ))17 ))
21 }18 }
22 19
23-/// Writes `name` in `dir` atomically: temp file, fsync, rename, then fsync the directory.
24 fn write_atomic(dir: &Path, name: &str, contents: &[u8], mode: u32) -> Result<()> {20 fn write_atomic(dir: &Path, name: &str, contents: &[u8], mode: u32) -> Result<()> {
25 let tmp = dir.join(format!(".{name}.tmp"));21 let tmp = dir.join(format!(".{name}.tmp"));
26 {22 {
@@ -38,7 +34,6 @@ fn write_atomic(dir: &Path, name: &str, contents: &[u8], mode: u32) -> Result<()
38 Ok(())34 Ok(())
39 }35 }
40 36
41-/// Writes `data_dir/gitconfig`: core.hooksPath, fsck, fsync, uploadpack and receive settings.
42 pub fn write_managed_gitconfig(data_dir: &Path) -> Result<()> {37 pub fn write_managed_gitconfig(data_dir: &Path) -> Result<()> {
43 if !data_dir.is_absolute() {38 if !data_dir.is_absolute() {
44 return Err(Error::InvalidInput(format!(39 return Err(Error::InvalidInput(format!(
@@ -52,9 +47,6 @@ pub fn write_managed_gitconfig(data_dir: &Path) -> Result<()> {
52 .ok_or_else(|| Error::InvalidInput("data dir is not valid UTF-8".into()))?;47 .ok_or_else(|| Error::InvalidInput("data dir is not valid UTF-8".into()))?;
53 let hooks = quote_config_value(hooks)?;48 let hooks = quote_config_value(hooks)?;
54 49
55- // `committed` hardens loose objects and packs; `reference` hardens ref updates.
56- // `uploadpack.allowRefInWant` stays off: with it, upload-pack writes wanted-refs before
57- // shallow-info, the client wants the reverse, and `git clone --depth` fails.
58 let body = format!(50 let body = format!(
59 "[core]\n\51 "[core]\n\
60 \thooksPath = {hooks}\n\52 \thooksPath = {hooks}\n\
@@ -83,8 +75,6 @@ pub fn write_managed_gitconfig(data_dir: &Path) -> Result<()> {
83 write_atomic(data_dir, "gitconfig", body.as_bytes(), 0o644)75 write_atomic(data_dir, "gitconfig", body.as_bytes(), 0o644)
84 }76 }
85 77
86-/// Writes `data_dir/hooks/{pre-receive,post-receive}` as `exec <forge_bin> hook <name>`, mode 0755.
87-/// `forge_bin` must be absolute and contain no quotes or control characters.
88 pub fn write_hook_shims(data_dir: &Path, forge_bin: &Path) -> Result<()> {78 pub fn write_hook_shims(data_dir: &Path, forge_bin: &Path) -> Result<()> {
89 let bin = forge_bin79 let bin = forge_bin
90 .to_str()80 .to_str()
crates/forge-git/src/tags.rsmodified+0 -12
@@ -1,17 +1,11 @@
1-//! Lightweight tag creation, used when a release names a tag that does not exist yet. Names are
2-//! checked against a strict allowlist, and object ids are validated, before anything reaches git.
3-
4 use std::path::Path;1 use std::path::Path;
5 2
6 use crate::command::GitEnv;3 use crate::command::GitEnv;
7 use crate::error::{Error, Result};4 use crate::error::{Error, Result};
8 use crate::history::{git, validate_oid, zero_oid};5 use crate::history::{git, validate_oid, zero_oid};
9 6
10-/// Longest tag name, in bytes.
11 const MAX_TAG_NAME_LEN: usize = 100;7 const MAX_TAG_NAME_LEN: usize = 100;
12 8
13-/// True for a tag name git accepts and forge allows: ASCII letters, digits and `._-+`, with no
14-/// slash, no `..`, no leading `.` or `-`, and no trailing `.` or `.lock`.
15 pub fn valid_tag_name(name: &str) -> bool {9 pub fn valid_tag_name(name: &str) -> bool {
16 !name.is_empty()10 !name.is_empty()
17 && name.len() <= MAX_TAG_NAME_LEN11 && name.len() <= MAX_TAG_NAME_LEN
@@ -24,8 +18,6 @@ pub fn valid_tag_name(name: &str) -> bool {
24 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-' | b'+'))18 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-' | b'+'))
25 }19 }
26 20
27-/// Creates `refs/tags/<name>` pointing at the commit `target`. The update requires that the tag
28-/// does not exist yet, so an existing tag is an error and is never moved.
29 pub async fn create_lightweight_tag(21 pub async fn create_lightweight_tag(
30 env: &GitEnv,22 env: &GitEnv,
31 repo: &Path,23 repo: &Path,
@@ -47,8 +39,6 @@ pub async fn create_lightweight_tag(
47 .await39 .await
48 }40 }
49 41
50-/// Moves `refs/tags/<name>` from `old` to `new`, but only if it still points at `old`. A stale
51-/// `old` gives `Error::RefMoved` and leaves the tag alone. The caller reads the tag first.
52 pub async fn move_lightweight_tag(42 pub async fn move_lightweight_tag(
53 env: &GitEnv,43 env: &GitEnv,
54 repo: &Path,44 repo: &Path,
@@ -83,8 +73,6 @@ pub async fn move_lightweight_tag(
83 }73 }
84 }74 }
85 75
86-/// The closest tag reachable from the parent of `oid`, as `(tag name, commit id)`. Lightweight and
87-/// annotated tags both count. `None` when no tag is reachable or `oid` has no parent.
88 pub async fn previous_tag(76 pub async fn previous_tag(
89 env: &GitEnv,77 env: &GitEnv,
90 repo: &Path,78 repo: &Path,
crates/forge-git/src/trailers.rsmodified+0 -9
@@ -1,7 +1,3 @@
1-//! `Co-authored-by:` trailers in a commit message.
2-//!
3-//! Trailers live in the message's last paragraph (the text after its last blank line).
4-
5 use std::collections::HashSet;1 use std::collections::HashSet;
6 2
7 const KEY: &str = "Co-authored-by";3 const KEY: &str = "Co-authored-by";
@@ -12,7 +8,6 @@ pub struct CoAuthor {
12 pub email: String,8 pub email: String,
13 }9 }
14 10
15-/// Co-authors from the message's trailer block, in order, deduplicated by lowercase email.
16 pub fn co_authors(message: &str) -> Vec<CoAuthor> {11 pub fn co_authors(message: &str) -> Vec<CoAuthor> {
17 let lines = lines(message);12 let lines = lines(message);
18 let mut seen = HashSet::new();13 let mut seen = HashSet::new();
@@ -23,7 +18,6 @@ pub fn co_authors(message: &str) -> Vec<CoAuthor> {
23 .collect()18 .collect()
24 }19 }
25 20
26-/// The message with every `Co-authored-by:` line removed and trailing blank lines trimmed.
27 pub fn strip_co_authors(message: &str) -> String {21 pub fn strip_co_authors(message: &str) -> String {
28 let lines = lines(message);22 let lines = lines(message);
29 let (head, tail) = lines.split_at(last_paragraph_start(&lines));23 let (head, tail) = lines.split_at(last_paragraph_start(&lines));
@@ -39,12 +33,10 @@ pub fn strip_co_authors(message: &str) -> String {
39 kept.join("\n").trim_end().to_owned()33 kept.join("\n").trim_end().to_owned()
40 }34 }
41 35
42-/// The message's lines with trailing whitespace removed from the end of the whole message.
43 fn lines(message: &str) -> Vec<&str> {36 fn lines(message: &str) -> Vec<&str> {
44 message.trim_end().lines().collect()37 message.trim_end().lines().collect()
45 }38 }
46 39
47-/// Index of the first line of the last paragraph; 0 when there is no blank line.
48 fn last_paragraph_start(lines: &[&str]) -> usize {40 fn last_paragraph_start(lines: &[&str]) -> usize {
49 lines41 lines
50 .iter()42 .iter()
@@ -57,7 +49,6 @@ fn trailer_value(line: &str) -> Option<&str> {
57 key.trim().eq_ignore_ascii_case(KEY).then_some(value)49 key.trim().eq_ignore_ascii_case(KEY).then_some(value)
58 }50 }
59 51
60-/// Parses `Co-authored-by: Name <email>`. Lines without a non-empty `<email>` give `None`.
61 fn parse(line: &str) -> Option<CoAuthor> {52 fn parse(line: &str) -> Option<CoAuthor> {
62 let value = trailer_value(line.trim())?.trim();53 let value = trailer_value(line.trim())?.trim();
63 let open = value.find('<')?;54 let open = value.find('<')?;
crates/forge-git/src/verify.rsmodified+0 -41
@@ -1,10 +1,3 @@
1-//! Commit signature verification through `git verify-commit`. Parses git's output into a
2-//! [`RawVerify`]. It does not decide ownership: forge-web matches the fingerprint to a user and
3-//! checks the committer email.
4-//!
5-//! The commit object is read first, so an unsigned commit never runs `verify-commit`. Every
6-//! commit id is checked as hex before it reaches git.
7-
8 use std::path::Path;1 use std::path::Path;
9 2
10 use forge_core::store::signatures::SigKind;3 use forge_core::store::signatures::SigKind;
@@ -13,24 +6,14 @@ use crate::command::{GitCommand, GitEnv};
13 use crate::error::{Error, Result};6 use crate::error::{Error, Result};
14 use crate::history::validate_oid;7 use crate::history::validate_oid;
15 8
16-/// What git said about one commit's signature.
17 #[derive(Debug, Clone, PartialEq, Eq)]9 #[derive(Debug, Clone, PartialEq, Eq)]
18 pub struct RawVerify {10 pub struct RawVerify {
19- /// False when the commit has no signature header. Every other field is then empty.
20 pub signed: bool,11 pub signed: bool,
21- /// From the signature header: `Ssh` for an SSH signature, `Gpg` for a PGP one.
22 pub kind: Option<SigKind>,12 pub kind: Option<SigKind>,
23- /// git reported a good signature.
24 pub good: bool,13 pub good: bool,
25- /// git reported a bad signature (`BADSIG`, or `Bad "git" signature`).
26 pub bad: bool,14 pub bad: bool,
27- /// The signing key is not known to git: `ERRSIG` or `NO_PUBKEY` for GPG, or `No principal
28- /// matched` for SSH.
29 pub missing_key: bool,15 pub missing_key: bool,
30- /// GPG: the primary key fingerprint, or the signing key's if git gave no primary. SSH: the
31- /// `SHA256:` fingerprint.
32 pub fingerprint: Option<String>,16 pub fingerprint: Option<String>,
33- /// SSH only: the allowed-signers principal that matched.
34 pub principal: Option<String>,17 pub principal: Option<String>,
35 }18 }
36 19
@@ -48,7 +31,6 @@ impl RawVerify {
48 }31 }
49 }32 }
50 33
51-/// The raw commit object (`git cat-file commit <oid>`).
52 async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>> {34 async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>> {
53 validate_oid(oid)?;35 validate_oid(oid)?;
54 GitCommand::new(env, "cat-file")36 GitCommand::new(env, "cat-file")
@@ -59,12 +41,9 @@ async fn commit_object(env: &GitEnv, repo: &Path, oid: &str) -> Result<Vec<u8>>
59 .await41 .await
60 }42 }
61 43
62-/// `None` when the commit has no `gpgsig` header. `Some(kind)` when it has one, where the kind is
63-/// read from the armor line (`None` if the armor is neither SSH nor PGP).
64 fn signature_header(object: &[u8]) -> Option<Option<SigKind>> {44 fn signature_header(object: &[u8]) -> Option<Option<SigKind>> {
65 for line in object.split(|&b| b == b'\n') {45 for line in object.split(|&b| b == b'\n') {
66 if line.is_empty() {46 if line.is_empty() {
67- // End of headers.
68 break;47 break;
69 }48 }
70 let value = line49 let value = line
@@ -83,7 +62,6 @@ fn signature_header(object: &[u8]) -> Option<Option<SigKind>> {
83 None62 None
84 }63 }
85 64
86-/// The committer email of a commit, without the angle brackets.
87 pub async fn committer_email(env: &GitEnv, repo: &Path, oid: &str) -> Result<String> {65 pub async fn committer_email(env: &GitEnv, repo: &Path, oid: &str) -> Result<String> {
88 let object = commit_object(env, repo, oid).await?;66 let object = commit_object(env, repo, oid).await?;
89 for line in object.split(|&b| b == b'\n') {67 for line in object.split(|&b| b == b'\n') {
@@ -105,11 +83,6 @@ pub async fn committer_email(env: &GitEnv, repo: &Path, oid: &str) -> Result<Str
105 Err(Error::Failed(format!("commit {oid} has no committer line")))83 Err(Error::Failed(format!("commit {oid} has no committer line")))
106 }84 }
107 85
108-/// Verifies the signature of `oid` in the repo at `repo` (a git dir). `allowed_signers` is the
109-/// SSH allowed-signers file. `gnupg_home`, when given, is the keyring for GPG signatures.
110-///
111-/// A non-zero exit from `verify-commit` is normal for a bad or unknown signature. The output is
112-/// parsed either way. Only a failure to start git is an error.
113 pub async fn verify_commit(86 pub async fn verify_commit(
114 env: &GitEnv,87 env: &GitEnv,
115 repo: &Path,88 repo: &Path,
@@ -139,8 +112,6 @@ pub async fn verify_commit(
139 Ok(parse_output(&text, kind))112 Ok(parse_output(&text, kind))
140 }113 }
141 114
142-/// Reads git's verification output. GPG status lines have the `[GNUPG:]` prefix. SSH results
143-/// are the `Good "git" signature` / `Bad "git" signature` sentences.
144 fn parse_output(text: &str, kind: Option<SigKind>) -> RawVerify {115 fn parse_output(text: &str, kind: Option<SigKind>) -> RawVerify {
145 let mut raw = RawVerify {116 let mut raw = RawVerify {
146 signed: true,117 signed: true,
@@ -153,7 +124,6 @@ fn parse_output(text: &str, kind: Option<SigKind>) -> RawVerify {
153 let mut parts = status.split_whitespace();124 let mut parts = status.split_whitespace();
154 match parts.next() {125 match parts.next() {
155 Some("VALIDSIG") => {126 Some("VALIDSIG") => {
156- // VALIDSIG <fpr> <date> <ts> <exp> <ver> <res> <pk> <hash> <class> [<primary>]
157 let fields: Vec<&str> = parts.collect();127 let fields: Vec<&str> = parts.collect();
158 let fpr = fields.get(9).or_else(|| fields.first());128 let fpr = fields.get(9).or_else(|| fields.first());
159 if let Some(fpr) = fpr {129 if let Some(fpr) = fpr {
@@ -169,8 +139,6 @@ fn parse_output(text: &str, kind: Option<SigKind>) -> RawVerify {
169 raw.missing_key = true;139 raw.missing_key = true;
170 } else if let Some(rest) = line.strip_prefix("Good \"git\" signature") {140 } else if let Some(rest) = line.strip_prefix("Good \"git\" signature") {
171 apply_ssh_sentence(&mut raw, rest);141 apply_ssh_sentence(&mut raw, rest);
172- // Without a principal the key matched no allowed signer. git still calls the
173- // signature good, but nobody vouches for the key, so it counts as an unknown key.
174 if raw.principal.is_some() {142 if raw.principal.is_some() {
175 raw.good = true;143 raw.good = true;
176 } else {144 } else {
@@ -184,8 +152,6 @@ fn parse_output(text: &str, kind: Option<SigKind>) -> RawVerify {
184 raw152 raw
185 }153 }
186 154
187-/// `rest` is what follows `Good "git" signature`: either ` for <principal> with <type> key
188-/// SHA256:<fp>` or ` with <type> key SHA256:<fp>`.
189 fn apply_ssh_sentence(raw: &mut RawVerify, rest: &str) {155 fn apply_ssh_sentence(raw: &mut RawVerify, rest: &str) {
190 if let Some(idx) = rest.strip_prefix(" for ").and_then(|s| s.find(" with ")) {156 if let Some(idx) = rest.strip_prefix(" for ").and_then(|s| s.find(" with ")) {
191 let after_for = &rest[" for ".len()..];157 let after_for = &rest[" for ".len()..];
@@ -202,7 +168,6 @@ mod tests {
202 use super::*;168 use super::*;
203 use std::process::Command;169 use std::process::Command;
204 170
205- /// A git invocation for test setup only, with no user or system config.
206 fn git(home: &Path, dir: &Path, args: &[&str]) -> String {171 fn git(home: &Path, dir: &Path, args: &[&str]) -> String {
207 let out = Command::new("git")172 let out = Command::new("git")
208 .arg("-C")173 .arg("-C")
@@ -230,7 +195,6 @@ mod tests {
230 }195 }
231 }196 }
232 197
233- /// Makes a repo with one unsigned commit by `email`, and returns (work dir, git dir).
234 fn repo_with_base(home: &Path, email: &str) -> (std::path::PathBuf, std::path::PathBuf) {198 fn repo_with_base(home: &Path, email: &str) -> (std::path::PathBuf, std::path::PathBuf) {
235 let work = home.join("work");199 let work = home.join("work");
236 std::fs::create_dir_all(&work).unwrap();200 std::fs::create_dir_all(&work).unwrap();
@@ -259,7 +223,6 @@ mod tests {
259 key223 key
260 }224 }
261 225
262- /// `allowed_signers` line for `email` from a `.pub` file.
263 fn allowed_line(pub_path: &Path, email: &str) -> String {226 fn allowed_line(pub_path: &Path, email: &str) -> String {
264 let text = std::fs::read_to_string(pub_path).unwrap();227 let text = std::fs::read_to_string(pub_path).unwrap();
265 let mut fields = text.split_whitespace();228 let mut fields = text.split_whitespace();
@@ -268,7 +231,6 @@ mod tests {
268 format!("{email} namespaces=\"git\" {algo} {blob}\n")231 format!("{email} namespaces=\"git\" {algo} {blob}\n")
269 }232 }
270 233
271- /// The SHA256 fingerprint of a `.pub` file, as `ssh-keygen -lf` prints it.
272 fn ssh_fingerprint(pub_path: &Path) -> String {234 fn ssh_fingerprint(pub_path: &Path) -> String {
273 let out = Command::new("ssh-keygen")235 let out = Command::new("ssh-keygen")
274 .arg("-lf")236 .arg("-lf")
@@ -360,7 +322,6 @@ mod tests {
360 let email = "tahinli@example.com";322 let email = "tahinli@example.com";
361 let (work, git_dir) = repo_with_base(home, email);323 let (work, git_dir) = repo_with_base(home, email);
362 let oid = git(home, &work, &["rev-parse", "HEAD"]);324 let oid = git(home, &work, &["rev-parse", "HEAD"]);
363- // The signers file does not exist. An unsigned commit must not reach verify-commit.
364 let signers = home.join("does-not-exist");325 let signers = home.join("does-not-exist");
365 326
366 let raw = verify_commit(&env_for(home), &git_dir, &oid, &signers, None)327 let raw = verify_commit(&env_for(home), &git_dir, &oid, &signers, None)
@@ -426,7 +387,6 @@ mod tests {
426 assert_eq!(signature_header(none), None);387 assert_eq!(signature_header(none), None);
427 }388 }
428 389
429- /// GPG round trip. Skipped when `gpg` is not installed.
430 #[tokio::test]390 #[tokio::test]
431 async fn gpg_good_signature_is_parsed() {391 async fn gpg_good_signature_is_parsed() {
432 if Command::new("gpg").arg("--version").output().is_err() {392 if Command::new("gpg").arg("--version").output().is_err() {
@@ -515,7 +475,6 @@ mod tests {
515 )475 )
516 .await476 .await
517 .unwrap();477 .unwrap();
518- // Stop the agent that gpg started for this keyring.
519 let _ = Command::new("gpgconf")478 let _ = Command::new("gpgconf")
520 .env("GNUPGHOME", &gnupg)479 .env("GNUPGHOME", &gnupg)
521 .args(["--kill", "gpg-agent"])480 .args(["--kill", "gpg-agent"])
crates/forge-git/src/version.rsmodified+0 -6
@@ -1,9 +1,6 @@
1-//! Git version detection. forge requires git 2.40.0 or newer.
2-
3 use crate::command::{GitCommand, GitEnv};1 use crate::command::{GitCommand, GitEnv};
4 use crate::error::{Error, Result};2 use crate::error::{Error, Result};
5 3
6-/// Parses `git version` output such as `git version 2.56.0` or `git version 2.39.2.windows.1`.
7 pub fn parse_git_version(output: &str) -> Option<(u32, u32, u32)> {4 pub fn parse_git_version(output: &str) -> Option<(u32, u32, u32)> {
8 let token = output5 let token = output
9 .split_whitespace()6 .split_whitespace()
@@ -15,7 +12,6 @@ pub fn parse_git_version(output: &str) -> Option<(u32, u32, u32)> {
15 Some((major, minor, patch))12 Some((major, minor, patch))
16 }13 }
17 14
18-/// The number at the start of `s`, so `0-rc1` yields 0.
19 fn leading_number(s: &str) -> Option<u32> {15 fn leading_number(s: &str) -> Option<u32> {
20 let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();16 let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
21 digits.parse().ok()17 digits.parse().ok()
@@ -25,7 +21,6 @@ pub fn fmt_version((major, minor, patch): (u32, u32, u32)) -> String {
25 format!("{major}.{minor}.{patch}")21 format!("{major}.{minor}.{patch}")
26 }22 }
27 23
28-/// Parses `git version` into (major, minor, patch).
29 pub async fn git_version(env: &GitEnv) -> Result<(u32, u32, u32)> {24 pub async fn git_version(env: &GitEnv) -> Result<(u32, u32, u32)> {
30 let out = GitCommand::new(env, "version").output().await?;25 let out = GitCommand::new(env, "version").output().await?;
31 let text = String::from_utf8_lossy(&out);26 let text = String::from_utf8_lossy(&out);
@@ -34,7 +29,6 @@ pub async fn git_version(env: &GitEnv) -> Result<(u32, u32, u32)> {
34 })29 })
35 }30 }
36 31
37-/// Fails with `Error::TooOld` if git is older than `min`.
38 pub async fn require_min_version(env: &GitEnv, min: (u32, u32, u32)) -> Result<()> {32 pub async fn require_min_version(env: &GitEnv, min: (u32, u32, u32)) -> Result<()> {
39 let found = git_version(env).await?;33 let found = git_version(env).await?;
40 if found < min {34 if found < min {
crates/forge-git/src/wiki.rsmodified+0 -28
@@ -1,8 +1,3 @@
1-//! Wiki storage. A repo's wiki is a second bare repo (see [`crate::repo::wiki_path`]) whose `main`
2-//! branch holds one `<Page-Name>.md` file per page. Web edits are commits made with git plumbing:
3-//! `hash-object`, a temporary index, `write-tree`, `commit-tree`, and a compare-and-swap
4-//! `update-ref`. Two edits to the same page therefore never overwrite each other silently.
5-
6 use std::path::{Path, PathBuf};1 use std::path::{Path, PathBuf};
7 use std::sync::atomic::{AtomicU64, Ordering};2 use std::sync::atomic::{AtomicU64, Ordering};
8 3
@@ -12,16 +7,11 @@ use crate::error::{Error, Result};
12 use crate::history::zero_oid;7 use crate::history::zero_oid;
13 use crate::repo::init_bare;8 use crate::repo::init_bare;
14 9
15-/// The branch that holds the pages.
16 pub const WIKI_BRANCH: &str = "main";10 pub const WIKI_BRANCH: &str = "main";
17-/// Extension of a page file.
18 const PAGE_EXT: &str = ".md";11 const PAGE_EXT: &str = ".md";
19-/// Largest page the editor accepts, and the largest one read back.
20 pub const MAX_PAGE_BYTES: usize = 256 * 1024;12 pub const MAX_PAGE_BYTES: usize = 256 * 1024;
21-/// Longest page name, in characters.
22 const MAX_PAGE_NAME: usize = 100;13 const MAX_PAGE_NAME: usize = 100;
23 14
24-/// One page edit. `name` is the page name without the extension.
25 #[derive(Debug, Clone, Copy)]15 #[derive(Debug, Clone, Copy)]
26 pub struct PageEdit<'a> {16 pub struct PageEdit<'a> {
27 pub name: &'a str,17 pub name: &'a str,
@@ -31,8 +21,6 @@ pub struct PageEdit<'a> {
31 pub author_email: &'a str,21 pub author_email: &'a str,
32 }22 }
33 23
34-/// True when `name` can name a page: 1 to 100 ASCII letters, digits, `-` or `_`, not starting with
35-/// `-`. Dashes stand for spaces in titles, so a page name never has a space or a slash.
36 pub fn valid_page_name(name: &str) -> bool {24 pub fn valid_page_name(name: &str) -> bool {
37 !name.is_empty()25 !name.is_empty()
38 && name.len() <= MAX_PAGE_NAME26 && name.len() <= MAX_PAGE_NAME
@@ -42,12 +30,10 @@ pub fn valid_page_name(name: &str) -> bool {
42 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')30 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
43 }31 }
44 32
45-/// The file that holds page `name` on the wiki branch.
46 pub fn page_file(name: &str) -> String {33 pub fn page_file(name: &str) -> String {
47 format!("{name}{PAGE_EXT}")34 format!("{name}{PAGE_EXT}")
48 }35 }
49 36
50-/// Creates the wiki repo when it is missing. Calling it again is harmless.
51 pub async fn ensure_wiki(env: &GitEnv, wiki: &Path) -> Result<()> {37 pub async fn ensure_wiki(env: &GitEnv, wiki: &Path) -> Result<()> {
52 if wiki.join("HEAD").is_file() {38 if wiki.join("HEAD").is_file() {
53 return Ok(());39 return Ok(());
@@ -55,7 +41,6 @@ pub async fn ensure_wiki(env: &GitEnv, wiki: &Path) -> Result<()> {
55 init_bare(env, wiki, WIKI_BRANCH).await41 init_bare(env, wiki, WIKI_BRANCH).await
56 }42 }
57 43
58-/// The commit at the tip of the wiki's `main`. `None` when the wiki is missing or has no page yet.
59 pub fn head_commit(wiki: &Path) -> Result<Option<String>> {44 pub fn head_commit(wiki: &Path) -> Result<Option<String>> {
60 if !wiki.join("HEAD").is_file() {45 if !wiki.join("HEAD").is_file() {
61 return Ok(None);46 return Ok(None);
@@ -63,7 +48,6 @@ pub fn head_commit(wiki: &Path) -> Result<Option<String>> {
63 default_branch_commit(wiki, WIKI_BRANCH)48 default_branch_commit(wiki, WIKI_BRANCH)
64 }49 }
65 50
66-/// Names of the pages at the head, sorted. Files that are not valid page names are skipped.
67 pub fn list_pages(wiki: &Path) -> Result<Vec<String>> {51 pub fn list_pages(wiki: &Path) -> Result<Vec<String>> {
68 let Some(head) = head_commit(wiki)? else {52 let Some(head) = head_commit(wiki)? else {
69 return Ok(Vec::new());53 return Ok(Vec::new());
@@ -82,8 +66,6 @@ pub fn list_pages(wiki: &Path) -> Result<Vec<String>> {
82 Ok(names)66 Ok(names)
83 }67 }
84 68
85-/// The Markdown source of page `name` at the head. `None` when the name is invalid, the page does
86-/// not exist, or it is not text.
87 pub fn read_page(wiki: &Path, name: &str) -> Result<Option<String>> {69 pub fn read_page(wiki: &Path, name: &str) -> Result<Option<String>> {
88 if !valid_page_name(name) {70 if !valid_page_name(name) {
89 return Ok(None);71 return Ok(None);
@@ -94,20 +76,16 @@ pub fn read_page(wiki: &Path, name: &str) -> Result<Option<String>> {
94 read_text_blob(wiki, &head, &page_file(name), MAX_PAGE_BYTES)76 read_text_blob(wiki, &head, &page_file(name), MAX_PAGE_BYTES)
95 }77 }
96 78
97-/// One commit that touched a page.
98 #[derive(Debug, Clone, PartialEq, Eq)]79 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub struct PageRevision {80 pub struct PageRevision {
100 pub oid: String,81 pub oid: String,
101 pub author: String,82 pub author: String,
102- /// Unix seconds of the author date.
103 pub at: i64,83 pub at: i64,
104 pub subject: String,84 pub subject: String,
105 }85 }
106 86
107-/// Most revisions `page_history` returns.
108 pub const HISTORY_LIMIT: usize = 200;87 pub const HISTORY_LIMIT: usize = 200;
109 88
110-/// Commits that touched page `name`, newest first, at most [`HISTORY_LIMIT`].
111 pub async fn page_history(env: &GitEnv, wiki: &Path, name: &str) -> Result<Vec<PageRevision>> {89 pub async fn page_history(env: &GitEnv, wiki: &Path, name: &str) -> Result<Vec<PageRevision>> {
112 if !valid_page_name(name) || head_commit(wiki)?.is_none() {90 if !valid_page_name(name) || head_commit(wiki)?.is_none() {
113 return Ok(Vec::new());91 return Ok(Vec::new());
@@ -138,7 +116,6 @@ pub async fn page_history(env: &GitEnv, wiki: &Path, name: &str) -> Result<Vec<P
138 116
139 static INDEX_SEQ: AtomicU64 = AtomicU64::new(0);117 static INDEX_SEQ: AtomicU64 = AtomicU64::new(0);
140 118
141-/// A temporary index file inside the wiki repo. Unique per process and call.
142 pub(crate) fn temp_index(wiki: &Path) -> PathBuf {119 pub(crate) fn temp_index(wiki: &Path) -> PathBuf {
143 let seq = INDEX_SEQ.fetch_add(1, Ordering::Relaxed);120 let seq = INDEX_SEQ.fetch_add(1, Ordering::Relaxed);
144 let nanos = std::time::SystemTime::now()121 let nanos = std::time::SystemTime::now()
@@ -148,9 +125,6 @@ pub(crate) fn temp_index(wiki: &Path) -> PathBuf {
148 wiki.join(format!("forge-index-{}-{nanos}-{seq}", std::process::id()))125 wiki.join(format!("forge-index-{}-{nanos}-{seq}", std::process::id()))
149 }126 }
150 127
151-/// Writes `edit` as a new commit on the wiki's `main`. `base` is the head the editor started from
152-/// (`None` when the wiki had no commits). The edit lands only if the head is still `base`; otherwise
153-/// it returns `Error::RefMoved` and writes nothing. Returns the new commit.
154 pub async fn commit_page(128 pub async fn commit_page(
155 env: &GitEnv,129 env: &GitEnv,
156 wiki: &Path,130 wiki: &Path,
@@ -174,7 +148,6 @@ pub async fn commit_page(
174 }148 }
175 let index = temp_index(wiki);149 let index = temp_index(wiki);
176 let result = write_commit(env, wiki, &index, base, edit).await;150 let result = write_commit(env, wiki, &index, base, edit).await;
177- // The index is scratch space. A leftover file is harmless, but do not keep it.
178 let _ = tokio::fs::remove_file(&index).await;151 let _ = tokio::fs::remove_file(&index).await;
179 result152 result
180 }153 }
@@ -236,7 +209,6 @@ async fn write_commit(
236 let oid = commit.output_stdin(edit.message.as_bytes()).await?;209 let oid = commit.output_stdin(edit.message.as_bytes()).await?;
237 let oid = String::from_utf8_lossy(&oid).trim().to_owned();210 let oid = String::from_utf8_lossy(&oid).trim().to_owned();
238 211
239- // Compare-and-swap: the ref must still hold `base`, or be absent when there was no base.
240 let old = match base {212 let old = match base {
241 Some(base) => base.to_owned(),213 Some(base) => base.to_owned(),
242 None => zero_oid(&oid),214 None => zero_oid(&oid),
crates/forge-git/tests/integration/browse_tools.rsmodified+0 -3
@@ -1,6 +1,3 @@
1-//! Tests for the code-browsing helpers: whitespace-free diffs, patches, the recursive file list,
2-//! blame and branch operations.
3-
4 use forge_git::blame::blame;1 use forge_git::blame::blame;
5 use forge_git::branches::{ahead_behind, create_branch, delete_branch};2 use forge_git::branches::{ahead_behind, create_branch, delete_branch};
6 use forge_git::command::ObjectSource;3 use forge_git::command::ObjectSource;
crates/forge-git/tests/integration/common.rsmodified+0 -2
@@ -1,5 +1,3 @@
1-//! Support shared by the integration test modules.
2-
3 use std::path::Path;1 use std::path::Path;
4 use std::path::PathBuf;2 use std::path::PathBuf;
5 use std::process::Command;3 use std::process::Command;
crates/forge-git/tests/integration/history.rsmodified+0 -1
@@ -235,7 +235,6 @@ async fn last_commits_finds_newest_touch_per_child() {
235 assert_eq!(root["d"].oid, c5);235 assert_eq!(root["d"].oid, c5);
236 assert_eq!(root["other.txt"].oid, c6);236 assert_eq!(root["other.txt"].oid, c6);
237 237
238- // max_walk counts commits in the pathspec-limited walk: c5 then c4.
239 let short = last_commits(&f.env, &f.git_dir, &c6, "d", &names, 1)238 let short = last_commits(&f.env, &f.git_dir, &c6, "d", &names, 1)
240 .await239 .await
241 .unwrap();240 .unwrap();
crates/forge-git/tests/integration/main.rsmodified+0 -2
@@ -1,5 +1,3 @@
1-//! forge-git integration tests. All modules compile into this single test binary.
2-
3 mod common;1 mod common;
4 2
5 mod browse;3 mod browse;
crates/forge-runner/build.rsmodified+0 -3
@@ -1,6 +1,3 @@
1-//! Emits the build identity (FORGE_GIT_SHA, FORGE_GIT_DATE, FORGE_GIT_DIRTY) for this binary.
2-//! The logic lives in forge-ci's build_identity.rs, shared with forge-web.
3-
4 include!("../forge-ci/build_identity.rs");1 include!("../forge-ci/build_identity.rs");
5 2
6 fn main() {3 fn main() {
crates/forge-runner/src/artifacts.rsmodified+0 -18
@@ -1,21 +1,12 @@
1-//! Artifact collection: expand a job's globs inside its workspace and flatten the matches into
2-//! upload names.
3-//!
4-//! The walk never follows symlinks, only regular files count, and every match is canonicalized
5-//! and checked to stay inside the canonical workspace.
6-
7 use std::collections::HashSet;1 use std::collections::HashSet;
8 use std::fs::FileType;2 use std::fs::FileType;
9 use std::path::{Path, PathBuf};3 use std::path::{Path, PathBuf};
10 4
11 use globset::{GlobBuilder, GlobSet, GlobSetBuilder};5 use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
12 6
13-/// The server accepts names matching `[A-Za-z0-9._+-]{1,128}` and not starting with `.`.
14 const MAX_NAME_LEN: usize = 128;7 const MAX_NAME_LEN: usize = 128;
15-/// The server caps artifacts per job at 50 by default.
16 const MAX_FILES: usize = 50;8 const MAX_FILES: usize = 50;
17 9
18-/// Errors from collecting artifacts. Any of them fails the job.
19 #[derive(Debug, thiserror::Error)]10 #[derive(Debug, thiserror::Error)]
20 pub enum ArtifactError {11 pub enum ArtifactError {
21 #[error("invalid artifact pattern {0:?}: must be relative, without ..")]12 #[error("invalid artifact pattern {0:?}: must be relative, without ..")]
@@ -34,17 +25,12 @@ pub enum ArtifactError {
34 Io(#[from] std::io::Error),25 Io(#[from] std::io::Error),
35 }26 }
36 27
37-/// One file to upload.
38 #[derive(Clone, Debug, PartialEq, Eq)]28 #[derive(Clone, Debug, PartialEq, Eq)]
39 pub struct Artifact {29 pub struct Artifact {
40- /// The flattened upload name.
41 pub name: String,30 pub name: String,
42- /// The file on disk, inside the workspace.
43 pub path: PathBuf,31 pub path: PathBuf,
44 }32 }
45 33
46-/// Turns a workspace-relative path into one upload name: `/` becomes `_`, characters outside
47-/// the server alphabet become `_`, and a leading `.` is replaced so the name is never hidden.
48 fn flatten_name(rel: &str) -> Result<String, ArtifactError> {34 fn flatten_name(rel: &str) -> Result<String, ArtifactError> {
49 let joined = rel35 let joined = rel
50 .split('/')36 .split('/')
@@ -70,7 +56,6 @@ fn flatten_name(rel: &str) -> Result<String, ArtifactError> {
70 Ok(name)56 Ok(name)
71 }57 }
72 58
73-/// Rejects patterns that are absolute or climb out of the workspace.
74 fn check_pattern(pattern: &str) -> Result<(), ArtifactError> {59 fn check_pattern(pattern: &str) -> Result<(), ArtifactError> {
75 let bad =60 let bad =
76 pattern.is_empty() || pattern.starts_with('/') || pattern.split('/').any(|c| c == "..");61 pattern.is_empty() || pattern.starts_with('/') || pattern.split('/').any(|c| c == "..");
@@ -90,7 +75,6 @@ fn build_globs(patterns: &[String]) -> Result<GlobSet, ArtifactError> {
90 Ok(builder.build()?)75 Ok(builder.build()?)
91 }76 }
92 77
93-/// Expands `patterns` inside `workspace`. Returns the matches sorted by name.
94 pub fn collect(78 pub fn collect(
95 workspace: &Path,79 workspace: &Path,
96 patterns: &[String],80 patterns: &[String],
@@ -117,7 +101,6 @@ pub fn collect(
117 } else {101 } else {
118 format!("{prefix}/{file_name}")102 format!("{prefix}/{file_name}")
119 };103 };
120- // DirEntry::file_type does not follow symlinks.
121 let file_type: FileType = entry.file_type()?;104 let file_type: FileType = entry.file_type()?;
122 if file_type.is_symlink() {105 if file_type.is_symlink() {
123 continue;106 continue;
@@ -140,7 +123,6 @@ pub fn collect(
140 let mut seen = HashSet::new();123 let mut seen = HashSet::new();
141 let mut out = Vec::with_capacity(found.len());124 let mut out = Vec::with_capacity(found.len());
142 for (rel, path) in found {125 for (rel, path) in found {
143- // Defense in depth: the walk never enters symlinks, but check the real location too.
144 let real = path.canonicalize()?;126 let real = path.canonicalize()?;
145 if !real.starts_with(&root) {127 if !real.starts_with(&root) {
146 continue;128 continue;
crates/forge-runner/src/cache.rsmodified+0 -99
@@ -1,20 +1,3 @@
1-//! The per-repo build cache. A job lists workspace paths to keep between runs (such as `target`).
2-//! When it finishes, those paths move out of its workspace into an entry. The next job for the
3-//! same repo, job name and cache key gets a copy, so the entry stays as it is until a finished
4-//! job replaces it. A cancelled or lost job never touches it.
5-//!
6-//! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids
7-//! never start with one:
8-//! - `<sha256 of repo, job name and key>/` is one entry. It holds `p0`, `p1`, ... for the cached
9-//! paths, `manifest.json` (the workspace path of each `pN`), `meta.json` and `stamps.json`.
10-//! - `.new-<job>` and `.old-<job>` are one job's scratch dirs. A crashed job can leave them behind,
11-//! and [`CacheStore::sweep_stale`] removes them at startup. `.inuse-<job>` is swept too: older
12-//! runners moved an entry there while a job used it.
13-//! - `.stamps-<job>` is one job's file of tracked-file stamps, written at restore and copied into
14-//! the entry at save. It sits here, not in the workspace, so the job cannot change it.
15-//!
16-//! A restore never fails a job. A failure is logged and the job runs without the cache.
17-
18 use std::collections::BTreeMap;1 use std::collections::BTreeMap;
19 use std::fs;2 use std::fs;
20 use std::io;3 use std::io;
@@ -30,20 +13,15 @@ use tokio::process::Command;
30 13
31 use crate::sandbox::idmap::{IdMap, remove_tree};14 use crate::sandbox::idmap::{IdMap, remove_tree};
32 15
33-/// Most paths one job may cache.
34 const MAX_PATHS: usize = 32;16 const MAX_PATHS: usize = 32;
35-/// Longest cached path, in bytes.
36 const MAX_PATH_LEN: usize = 512;17 const MAX_PATH_LEN: usize = 512;
37-/// Longest cache key, in bytes.
38 const MAX_KEY_LEN: usize = 256;18 const MAX_KEY_LEN: usize = 256;
39-/// Longest `cp` stderr kept for a log line, in characters.
40 const MAX_STDERR: usize = 500;19 const MAX_STDERR: usize = 500;
41 const MANIFEST: &str = "manifest.json";20 const MANIFEST: &str = "manifest.json";
42 const META: &str = "meta.json";21 const META: &str = "meta.json";
43 const STAMPS: &str = "stamps.json";22 const STAMPS: &str = "stamps.json";
44 const SCRATCH_PREFIXES: [&str; 4] = [".inuse-", ".new-", ".old-", ".stamps-"];23 const SCRATCH_PREFIXES: [&str; 4] = [".inuse-", ".new-", ".old-", ".stamps-"];
45 24
46-/// Errors from the build cache. They are logged to the job, never returned to the forge.
47 #[derive(Debug, thiserror::Error)]25 #[derive(Debug, thiserror::Error)]
48 pub enum CacheError {26 pub enum CacheError {
49 #[error("cache io: {0}")]27 #[error("cache io: {0}")]
@@ -60,57 +38,44 @@ pub enum CacheError {
60 Git(String),38 Git(String),
61 }39 }
62 40
63-/// One tracked file's stamp: the blob it had and the mtime it was given, in Unix seconds.
64 #[derive(Debug, Clone, Serialize, Deserialize)]41 #[derive(Debug, Clone, Serialize, Deserialize)]
65 struct Stamp {42 struct Stamp {
66 blob: String,43 blob: String,
67 mtime: i64,44 mtime: i64,
68 }45 }
69 46
70-/// Tracked file path to its stamp. Read from `stamps.json`, and written to the job's scratch file.
71 type Stamps = BTreeMap<String, Stamp>;47 type Stamps = BTreeMap<String, Stamp>;
72 48
73-/// What one restored entry gave the job: its size and the stamps it recorded.
74 struct Restored {49 struct Restored {
75 size: u64,50 size: u64,
76 stamps: Stamps,51 stamps: Stamps,
77 }52 }
78 53
79-/// What `meta.json` records about one entry.
80 #[derive(Debug, Serialize, Deserialize)]54 #[derive(Debug, Serialize, Deserialize)]
81 struct Meta {55 struct Meta {
82 repo: String,56 repo: String,
83 job: String,57 job: String,
84 key: String,58 key: String,
85- /// When the entry was saved, in Unix nanoseconds. Eviction removes the oldest first.
86 saved_at: u64,59 saved_at: u64,
87 size_bytes: u64,60 size_bytes: u64,
88 }61 }
89 62
90-/// One entry found while evicting.
91 struct Found {63 struct Found {
92 path: PathBuf,64 path: PathBuf,
93 size: u64,65 size: u64,
94 saved_at: u64,66 saved_at: u64,
95 }67 }
96 68
97-/// The build cache of one runner. Shared by every job the runner runs.
98 pub struct CacheStore {69 pub struct CacheStore {
99 root: PathBuf,70 root: PathBuf,
100- /// The cap on the total size of all entries. Zero means the cache is off.
101 max_bytes: u64,71 max_bytes: u64,
102 idmap: IdMap,72 idmap: IdMap,
103 helper: PathBuf,73 helper: PathBuf,
104- /// Read while an entry is copied into a workspace, written while one is installed or evicted,
105- /// so a copy never sees its entry swapped or removed halfway.
106 lock: tokio::sync::RwLock<()>,74 lock: tokio::sync::RwLock<()>,
107- /// The last save stamp, so entries saved in the same nanosecond still order by save time.
108 last_stamp: AtomicU64,75 last_stamp: AtomicU64,
109 }76 }
110 77
111 impl CacheStore {78 impl CacheStore {
112- /// `root` holds the entries and `max_bytes` caps their total size. `idmap` and `helper` remove
113- /// dirs whose files may be owned by subordinate ids (see [`remove_tree`]).
114 pub fn new(root: PathBuf, max_bytes: u64, idmap: IdMap, helper: PathBuf) -> Self {79 pub fn new(root: PathBuf, max_bytes: u64, idmap: IdMap, helper: PathBuf) -> Self {
115 Self {80 Self {
116 root,81 root,
@@ -122,7 +87,6 @@ impl CacheStore {
122 }87 }
123 }88 }
124 89
125- /// Removes the scratch dirs of jobs that crashed. Call once at startup, before any job runs.
126 pub async fn sweep_stale(&self) -> Result<(), CacheError> {90 pub async fn sweep_stale(&self) -> Result<(), CacheError> {
127 let mut dir = match tokio::fs::read_dir(&self.root).await {91 let mut dir = match tokio::fs::read_dir(&self.root).await {
128 Ok(dir) => dir,92 Ok(dir) => dir,
@@ -142,8 +106,6 @@ impl CacheStore {
142 Ok(())106 Ok(())
143 }107 }
144 108
145- /// Puts the job's cached paths into `workspace` before the run. Returns the job log lines.
146- /// Never fails: a failed restore is logged and the job runs uncached.
147 pub async fn restore(&self, job: &JobAssignment, workspace: &Path) -> Vec<String> {109 pub async fn restore(&self, job: &JobAssignment, workspace: &Path) -> Vec<String> {
148 let mut lines = Vec::new();110 let mut lines = Vec::new();
149 if job.cache.is_empty() || self.max_bytes == 0 {111 if job.cache.is_empty() || self.max_bytes == 0 {
@@ -192,9 +154,6 @@ impl CacheStore {
192 lines154 lines
193 }155 }
194 156
195- /// Moves the job's cached paths out of `workspace` into the entry for `job.cache_key`. Only a
196- /// finished job saves, with Success or Failure. Returns the job log lines. Never fails. The
197- /// job's scratch dirs are always removed, whatever happened.
198 pub async fn save(157 pub async fn save(
199 &self,158 &self,
200 job: &JobAssignment,159 job: &JobAssignment,
@@ -219,8 +178,6 @@ impl CacheStore {
219 lines178 lines
220 }179 }
221 180
222- /// Copies the entry for `key`'s wanted paths into the workspace. The entry is left as it is.
223- /// Returns the entry size and stamps when at least one path was restored.
224 async fn restore_from(181 async fn restore_from(
225 &self,182 &self,
226 job: &JobAssignment,183 job: &JobAssignment,
@@ -241,7 +198,6 @@ impl CacheStore {
241 return None;198 return None;
242 }199 }
243 };200 };
244- // Read under the lock, so the stamps belong to the entry copied here.
245 let stamps = read_stamps(&source);201 let stamps = read_stamps(&source);
246 let mut restored = 0usize;202 let mut restored = 0usize;
247 for (k, rel) in selected(&manifest, wanted, lines) {203 for (k, rel) in selected(&manifest, wanted, lines) {
@@ -265,9 +221,6 @@ impl CacheStore {
265 Some(Restored { size, stamps })221 Some(Restored { size, stamps })
266 }222 }
267 223
268- /// Sets each tracked file's mtime to when its content last changed. A file whose blob matches
269- /// `previous` keeps that stamp, and any other file gets the current time. The new stamps go to
270- /// the job's scratch file for the save. Never fails the job.
271 async fn stamp_files(224 async fn stamp_files(
272 &self,225 &self,
273 job: &JobAssignment,226 job: &JobAssignment,
@@ -287,15 +240,12 @@ impl CacheStore {
287 }240 }
288 }241 }
289 242
290- /// The work of [`CacheStore::stamp_files`]. Returns how many files kept their stamp and how
291- /// many got the current time.
292 async fn try_stamp_files(243 async fn try_stamp_files(
293 &self,244 &self,
294 job: &JobAssignment,245 job: &JobAssignment,
295 workspace: &Path,246 workspace: &Path,
296 previous: &Stamps,247 previous: &Stamps,
297 ) -> Result<(usize, usize), CacheError> {248 ) -> Result<(usize, usize), CacheError> {
298- // The checkout is at the job's commit, so HEAD lists exactly the tracked files.
299 let listing = Command::new("git")249 let listing = Command::new("git")
300 .arg("-C")250 .arg("-C")
301 .arg(workspace)251 .arg(workspace)
@@ -317,7 +267,6 @@ impl CacheStore {
317 let mut stamps = Stamps::new();267 let mut stamps = Stamps::new();
318 let mut files = Vec::new();268 let mut files = Vec::new();
319 let (mut kept, mut changed) = (0usize, 0usize);269 let (mut kept, mut changed) = (0usize, 0usize);
320- // Records are `<mode> <type> <oid>\t<path>`, NUL terminated. Only regular files count.
321 for record in listing.stdout.split(|b| *b == 0).filter(|r| !r.is_empty()) {270 for record in listing.stdout.split(|b| *b == 0).filter(|r| !r.is_empty()) {
322 let Some(tab) = record.iter().position(|b| *b == b'\t') else {271 let Some(tab) = record.iter().position(|b| *b == b'\t') else {
323 continue;272 continue;
@@ -358,21 +307,17 @@ impl CacheStore {
358 307
359 tokio::task::spawn_blocking(move || {308 tokio::task::spawn_blocking(move || {
360 for (path, secs) in &files {309 for (path, secs) in &files {
361- // A file that cannot be stamped keeps its checkout time. That is not a failure.
362 let _ = time_of(*secs).and_then(|time| set_mtime(path, time));310 let _ = time_of(*secs).and_then(|time| set_mtime(path, time));
363 }311 }
364 })312 })
365 .await313 .await
366 .map_err(io::Error::other)?;314 .map_err(io::Error::other)?;
367 315
368- // A first job on a fresh runner gets here before any save has made the root.
369 tokio::fs::create_dir_all(&self.root).await?;316 tokio::fs::create_dir_all(&self.root).await?;
370 write_json(&self.scratch(".stamps-", &job.job_id), &stamps).await?;317 write_json(&self.scratch(".stamps-", &job.job_id), &stamps).await?;
371 Ok((kept, changed))318 Ok((kept, changed))
372 }319 }
373 320
374- /// Builds the new entry in `.new-<job>` and installs it over the old one. Caller has checked
375- /// that the outcome, key and paths allow a save.
376 async fn save_paths(321 async fn save_paths(
377 &self,322 &self,
378 job: &JobAssignment,323 job: &JobAssignment,
@@ -406,9 +351,7 @@ impl CacheStore {
406 return Ok(());351 return Ok(());
407 }352 }
408 353
409- // Measured before the metadata files are written, so the size is the cached data only.
410 let size = dir_size(&new).await;354 let size = dir_size(&new).await;
411- // The stamps the job's restore wrote. Missing when the restore did not get that far.
412 let stamps = self.scratch(".stamps-", &job.job_id);355 let stamps = self.scratch(".stamps-", &job.job_id);
413 if exists_no_follow(&stamps) {356 if exists_no_follow(&stamps) {
414 tokio::fs::copy(&stamps, new.join(STAMPS)).await?;357 tokio::fs::copy(&stamps, new.join(STAMPS)).await?;
@@ -434,7 +377,6 @@ impl CacheStore {
434 }377 }
435 if let Err(e) = tokio::fs::rename(&new, &entry).await {378 if let Err(e) = tokio::fs::rename(&new, &entry).await {
436 if had_old {379 if had_old {
437- // Put the previous entry back, so a failed save loses nothing.
438 let _ = tokio::fs::rename(&old, &entry).await;380 let _ = tokio::fs::rename(&old, &entry).await;
439 }381 }
440 return Err(e.into());382 return Err(e.into());
@@ -449,8 +391,6 @@ impl CacheStore {
449 Ok(())391 Ok(())
450 }392 }
451 393
452- /// Removes the least recently saved entries until the total is within the cap. The caller
453- /// holds the lock. Returns how many entries went.
454 async fn evict(&self) -> Result<usize, CacheError> {394 async fn evict(&self) -> Result<usize, CacheError> {
455 let mut entries = self.list_entries().await?;395 let mut entries = self.list_entries().await?;
456 let mut total = entries396 let mut total = entries
@@ -469,8 +409,6 @@ impl CacheStore {
469 Ok(removed)409 Ok(removed)
470 }410 }
471 411
472- /// Every entry under the root. An entry without a readable `meta.json` is sized by walking it,
473- /// and its save time is the dir's mtime.
474 async fn list_entries(&self) -> Result<Vec<Found>, CacheError> {412 async fn list_entries(&self) -> Result<Vec<Found>, CacheError> {
475 let mut found = Vec::new();413 let mut found = Vec::new();
476 let mut dir = match tokio::fs::read_dir(&self.root).await {414 let mut dir = match tokio::fs::read_dir(&self.root).await {
@@ -508,7 +446,6 @@ impl CacheStore {
508 Ok(found)446 Ok(found)
509 }447 }
510 448
511- /// A save time in Unix nanoseconds, larger than every earlier one from this store.
512 fn stamp(&self) -> u64 {449 fn stamp(&self) -> u64 {
513 let now = nanos(450 let now = nanos(
514 SystemTime::now()451 SystemTime::now()
@@ -536,7 +473,6 @@ impl CacheStore {
536 self.root.join(format!("{prefix}{job_id}"))473 self.root.join(format!("{prefix}{job_id}"))
537 }474 }
538 475
539- /// Removes all of one job's scratch dirs. Missing ones are fine.
540 async fn remove_scratch(&self, job_id: &str) -> Result<(), CacheError> {476 async fn remove_scratch(&self, job_id: &str) -> Result<(), CacheError> {
541 for prefix in SCRATCH_PREFIXES {477 for prefix in SCRATCH_PREFIXES {
542 self.remove(&self.scratch(prefix, job_id)).await?;478 self.remove(&self.scratch(prefix, job_id)).await?;
@@ -544,8 +480,6 @@ impl CacheStore {
544 Ok(())480 Ok(())
545 }481 }
546 482
547- /// Removes a file or dir tree, through the id map so subuid-owned files go too. Blocking work
548- /// runs off the async runtime.
549 async fn remove(&self, path: &Path) -> Result<(), CacheError> {483 async fn remove(&self, path: &Path) -> Result<(), CacheError> {
550 let (map, helper, path) = (self.idmap.clone(), self.helper.clone(), path.to_owned());484 let (map, helper, path) = (self.idmap.clone(), self.helper.clone(), path.to_owned());
551 tokio::task::spawn_blocking(move || remove_tree(&map, &path, &helper))485 tokio::task::spawn_blocking(move || remove_tree(&map, &path, &helper))
@@ -555,8 +489,6 @@ impl CacheStore {
555 }489 }
556 }490 }
557 491
558-/// Checks one cached path from the forge, and again on the runner. It must be a relative path
559-/// with no empty, `.`, `..` or `.git` parts.
560 pub fn validate_path(path: &str) -> Result<PathBuf, CacheError> {492 pub fn validate_path(path: &str) -> Result<PathBuf, CacheError> {
561 let refuse = |reason: &'static str| CacheError::Path {493 let refuse = |reason: &'static str| CacheError::Path {
562 path: path.to_owned(),494 path: path.to_owned(),
@@ -586,7 +518,6 @@ pub fn validate_path(path: &str) -> Result<PathBuf, CacheError> {
586 Ok(out)518 Ok(out)
587 }519 }
588 520
589-/// Checks the whole list: at most [`MAX_PATHS`] paths, each valid, and none inside another.
590 pub fn validate_paths(paths: &[String]) -> Result<Vec<PathBuf>, CacheError> {521 pub fn validate_paths(paths: &[String]) -> Result<Vec<PathBuf>, CacheError> {
591 if paths.len() > MAX_PATHS {522 if paths.len() > MAX_PATHS {
592 return Err(CacheError::Path {523 return Err(CacheError::Path {
@@ -611,8 +542,6 @@ pub fn validate_paths(paths: &[String]) -> Result<Vec<PathBuf>, CacheError> {
611 Ok(parsed)542 Ok(parsed)
612 }543 }
613 544
614-/// The manifest entries the job asked for, as (index, path). An entry that fails validation is
615-/// logged and dropped.
616 fn selected(545 fn selected(
617 manifest: &[String],546 manifest: &[String],
618 wanted: &[PathBuf],547 wanted: &[PathBuf],
@@ -629,9 +558,6 @@ fn selected(
629 out558 out
630 }559 }
631 560
632-/// The workspace path for `rel`. Missing parent dirs are created when `create` is set. Each parent
633-/// is checked one component at a time, and a symlink there is refused, never followed. Returns
634-/// `None` when a parent is missing and `create` is not set.
635 fn workspace_path(561 fn workspace_path(
636 workspace: &Path,562 workspace: &Path,
637 rel: &Path,563 rel: &Path,
@@ -672,7 +598,6 @@ fn workspace_path(
672 Ok(Some(cur.join(name)))598 Ok(Some(cur.join(name)))
673 }599 }
674 600
675-/// The workspace path of `rel` when something exists there. `None` when nothing does.
676 fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result<Option<PathBuf>, CacheError> {601 fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result<Option<PathBuf>, CacheError> {
677 let Some(path) = workspace_path(workspace, rel, false)? else {602 let Some(path) = workspace_path(workspace, rel, false)? else {
678 return Ok(None);603 return Ok(None);
@@ -680,8 +605,6 @@ fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result<Option<PathBuf>
680 Ok(exists_no_follow(&path).then_some(path))605 Ok(exists_no_follow(&path).then_some(path))
681 }606 }
682 607
683-/// Copies `src` to `workspace/rel` with `cp -a --reflink=auto`. The source is left in place.
684-/// Returns false when the checkout already has something there.
685 async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> {608 async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> {
686 let Some(dest) = workspace_path(workspace, rel, true)? else {609 let Some(dest) = workspace_path(workspace, rel, true)? else {
687 return Ok(false);610 return Ok(false);
@@ -702,7 +625,6 @@ async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, Cac
702 if output.status.success() {625 if output.status.success() {
703 return Ok(true);626 return Ok(true);
704 }627 }
705- // A partial copy must not stay in the checkout.
706 let _ = plain_remove(&dest).await;628 let _ = plain_remove(&dest).await;
707 let stderr: String = String::from_utf8_lossy(&output.stderr)629 let stderr: String = String::from_utf8_lossy(&output.stderr)
708 .chars()630 .chars()
@@ -711,8 +633,6 @@ async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, Cac
711 Err(CacheError::Copy(stderr.trim().to_owned()))633 Err(CacheError::Copy(stderr.trim().to_owned()))
712 }634 }
713 635
714-/// Removes a file, symlink or dir tree the runner owns. The checkout is never subuid-owned at
715-/// this point, so no id map is needed.
716 async fn plain_remove(path: &Path) -> io::Result<()> {636 async fn plain_remove(path: &Path) -> io::Result<()> {
717 match fs::symlink_metadata(path) {637 match fs::symlink_metadata(path) {
718 Ok(meta) if meta.is_dir() => tokio::fs::remove_dir_all(path).await,638 Ok(meta) if meta.is_dir() => tokio::fs::remove_dir_all(path).await,
@@ -726,7 +646,6 @@ fn read_meta(dir: &Path) -> Option<Meta> {
726 serde_json::from_slice(&bytes).ok()646 serde_json::from_slice(&bytes).ok()
727 }647 }
728 648
729-/// The stamps an entry recorded. An entry without a readable `stamps.json` has none.
730 fn read_stamps(dir: &Path) -> Stamps {649 fn read_stamps(dir: &Path) -> Stamps {
731 fs::read(dir.join(STAMPS))650 fs::read(dir.join(STAMPS))
732 .ok()651 .ok()
@@ -734,7 +653,6 @@ fn read_stamps(dir: &Path) -> Stamps {
734 .unwrap_or_default()653 .unwrap_or_default()
735 }654 }
736 655
737-/// Sets a regular file's modification time. A symlink or other kind is refused, not followed.
738 fn set_mtime(path: &Path, time: SystemTime) -> io::Result<()> {656 fn set_mtime(path: &Path, time: SystemTime) -> io::Result<()> {
739 if !fs::symlink_metadata(path)?.is_file() {657 if !fs::symlink_metadata(path)?.is_file() {
740 return Err(io::Error::other("not a regular file"));658 return Err(io::Error::other("not a regular file"));
@@ -742,7 +660,6 @@ fn set_mtime(path: &Path, time: SystemTime) -> io::Result<()> {
742 fs::File::open(path)?.set_modified(time)660 fs::File::open(path)?.set_modified(time)
743 }661 }
744 662
745-/// A stamp's Unix seconds as a time. Negative or out of range values are refused.
746 fn time_of(secs: i64) -> io::Result<SystemTime> {663 fn time_of(secs: i64) -> io::Result<SystemTime> {
747 u64::try_from(secs)664 u64::try_from(secs)
748 .ok()665 .ok()
@@ -750,7 +667,6 @@ fn time_of(secs: i64) -> io::Result<SystemTime> {
750 .ok_or_else(|| io::Error::other("time out of range"))667 .ok_or_else(|| io::Error::other("time out of range"))
751 }668 }
752 669
753-/// Unix seconds of `now`, or 0 before the epoch.
754 fn unix_secs(now: SystemTime) -> i64 {670 fn unix_secs(now: SystemTime) -> i64 {
755 now.duration_since(UNIX_EPOCH)671 now.duration_since(UNIX_EPOCH)
756 .ok()672 .ok()
@@ -769,8 +685,6 @@ async fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), CacheErr
769 Ok(())685 Ok(())
770 }686 }
771 687
772-/// The total size of the files under `root`. Symlinks count as links and are never followed.
773-/// Unreadable dirs count as empty. Runs off the async runtime.
774 async fn dir_size(root: &Path) -> u64 {688 async fn dir_size(root: &Path) -> u64 {
775 let root = root.to_owned();689 let root = root.to_owned();
776 tokio::task::spawn_blocking(move || tree_size(&root))690 tokio::task::spawn_blocking(move || tree_size(&root))
@@ -799,7 +713,6 @@ fn tree_size(root: &Path) -> u64 {
799 total713 total
800 }714 }
801 715
802-/// The entry directory name for one job's cache key. Hashing keeps key text out of paths.
803 fn entry_name(repo: &str, job_name: &str, key: &str) -> String {716 fn entry_name(repo: &str, job_name: &str, key: &str) -> String {
804 let mut hash = Sha256::new();717 let mut hash = Sha256::new();
805 hash.update(repo.as_bytes());718 hash.update(repo.as_bytes());
@@ -810,7 +723,6 @@ fn entry_name(repo: &str, job_name: &str, key: &str) -> String {
810 hex::encode(hash.finalize())723 hex::encode(hash.finalize())
811 }724 }
812 725
813-/// Whether a dir name is an entry: 64 lowercase hex digits.
814 fn is_entry_name(name: &str) -> bool {726 fn is_entry_name(name: &str) -> bool {
815 name.len() == 64727 name.len() == 64
816 && name728 && name
@@ -841,7 +753,6 @@ fn skipped(rel: &Path) -> String {
841 )753 )
842 }754 }
843 755
844-/// A size for log lines, such as `3.1 GiB`.
845 fn human(bytes: u64) -> String {756 fn human(bytes: u64) -> String {
846 const KIB: f64 = 1024.0;757 const KIB: f64 = 1024.0;
847 let b = bytes as f64;758 let b = bytes as f64;
@@ -893,7 +804,6 @@ mod tests {
893 )804 )
894 }805 }
895 806
896- /// A workspace `dir/<name>` holding `target/a.txt` with `body`.
897 fn workspace(dir: &Path, name: &str, body: &str) -> PathBuf {807 fn workspace(dir: &Path, name: &str, body: &str) -> PathBuf {
898 let ws = dir.join(name);808 let ws = dir.join(name);
899 fs::create_dir_all(ws.join("target")).expect("mkdir");809 fs::create_dir_all(ws.join("target")).expect("mkdir");
@@ -939,13 +849,11 @@ mod tests {
939 );849 );
940 assert_eq!(read(&ws2.join("target/a.txt")), "one");850 assert_eq!(read(&ws2.join("target/a.txt")), "one");
941 851
942- // A cancelled job leaves the entry as it was.
943 fs::write(ws2.join("target/a.txt"), "half").expect("write");852 fs::write(ws2.join("target/a.txt"), "half").expect("write");
944 store.save(&second, Outcome::Cancelled, &ws2).await;853 store.save(&second, Outcome::Cancelled, &ws2).await;
945 let entry = entry_of(&store, "ref:refs/heads/main");854 let entry = entry_of(&store, "ref:refs/heads/main");
946 assert_eq!(read(&entry.join("p0/a.txt")), "one");855 assert_eq!(read(&entry.join("p0/a.txt")), "one");
947 856
948- // Another job hits the same entry, and its finished save replaces it.
949 let third = job("job_c", "ref:refs/heads/main", &[], &["target"]);857 let third = job("job_c", "ref:refs/heads/main", &[], &["target"]);
950 let ws3 = empty_workspace(dir.path(), "ws_c");858 let ws3 = empty_workspace(dir.path(), "ws_c");
951 store.restore(&third, &ws3).await;859 store.restore(&third, &ws3).await;
@@ -1043,7 +951,6 @@ mod tests {
1043 "main"951 "main"
1044 );952 );
1045 953
1046- // A job whose own key is empty saves nothing, even with restore keys listed.
1047 let none = job("job_n", "", &["ref:refs/heads/main"], &["target"]);954 let none = job("job_n", "", &["ref:refs/heads/main"], &["target"]);
1048 store955 store
1049 .save(956 .save(
@@ -1078,7 +985,6 @@ mod tests {
1078 #[tokio::test]985 #[tokio::test]
1079 async fn eviction_removes_the_least_recently_saved_entry() {986 async fn eviction_removes_the_least_recently_saved_entry() {
1080 let dir = tempfile::tempdir().expect("tempdir");987 let dir = tempfile::tempdir().expect("tempdir");
1081- // Each entry holds 1000 bytes. The cap fits two of them.
1082 let store = store(dir.path(), 2500);988 let store = store(dir.path(), 2500);
1083 for key in ["k1", "k2", "k3"] {989 for key in ["k1", "k2", "k3"] {
1084 let ws = dir.path().join(format!("ws_{key}"));990 let ws = dir.path().join(format!("ws_{key}"));
@@ -1136,7 +1042,6 @@ mod tests {
1136 let first = job("job_1", "ref:main", &[], &["build/out"]);1042 let first = job("job_1", "ref:main", &[], &["build/out"]);
1137 store.save(&first, Outcome::Success, &ws1).await;1043 store.save(&first, Outcome::Success, &ws1).await;
1138 1044
1139- // Restore into a checkout where `build` is a symlink out of the workspace.
1140 let ws2 = empty_workspace(dir.path(), "ws2");1045 let ws2 = empty_workspace(dir.path(), "ws2");
1141 symlink(&outside, ws2.join("build")).expect("symlink");1046 symlink(&outside, ws2.join("build")).expect("symlink");
1142 let second = job("job_2", "ref:main", &[], &["build/out"]);1047 let second = job("job_2", "ref:main", &[], &["build/out"]);
@@ -1152,7 +1057,6 @@ mod tests {
1152 "restore must not write through the symlink"1057 "restore must not write through the symlink"
1153 );1058 );
1154 1059
1155- // Save from a checkout with the same symlink: nothing is moved out of `outside`.
1156 fs::create_dir_all(outside.join("out")).expect("mkdir");1060 fs::create_dir_all(outside.join("out")).expect("mkdir");
1157 let ws3 = empty_workspace(dir.path(), "ws3");1061 let ws3 = empty_workspace(dir.path(), "ws3");
1158 symlink(&outside, ws3.join("build")).expect("symlink");1062 symlink(&outside, ws3.join("build")).expect("symlink");
@@ -1184,7 +1088,6 @@ mod tests {
1184 assert!(keep.is_dir(), "entries are kept");1088 assert!(keep.is_dir(), "entries are kept");
1185 }1089 }
1186 1090
1187- /// Runs git in `dir` with a fixed identity. Fails the test when git fails.
1188 fn git(dir: &Path, args: &[&str]) {1091 fn git(dir: &Path, args: &[&str]) {
1189 let ok = std::process::Command::new("git")1092 let ok = std::process::Command::new("git")
1190 .arg("-C")1093 .arg("-C")
@@ -1232,7 +1135,6 @@ mod tests {
1232 ],1135 ],
1233 );1136 );
1234 1137
1235- // The first run is a miss. It saves an entry from its checkout.
1236 git(dir.path(), &["clone", "--quiet", &origin_str, "ws1"]);1138 git(dir.path(), &["clone", "--quiet", &origin_str, "ws1"]);
1237 let ws1 = dir.path().join("ws1");1139 let ws1 = dir.path().join("ws1");
1238 let first = job("job_1", "ref:main", &[], &["target"]);1140 let first = job("job_1", "ref:main", &[], &["target"]);
@@ -1242,7 +1144,6 @@ mod tests {
1242 store.save(&first, Outcome::Success, &ws1).await;1144 store.save(&first, Outcome::Success, &ws1).await;
1243 let a_stamp = mtime_secs(&ws1.join("a.txt"));1145 let a_stamp = mtime_secs(&ws1.join("a.txt"));
1244 1146
1245- // The next commit changes only b.txt. The sleep makes a new stamp a later second.
1246 fs::write(origin.join("b.txt"), "b2").expect("write");1147 fs::write(origin.join("b.txt"), "b2").expect("write");
1247 git(&origin, &["add", "."]);1148 git(&origin, &["add", "."]);
1248 git(1149 git(
crates/forge-runner/src/check.rsmodified+0 -30
@@ -1,9 +1,3 @@
1-//! Host checks for the builtin executor, behind `forge-runner check`.
2-//!
3-//! The check runs one trivial job through the real sandbox, with a rootfs of host binaries, and
4-//! reports each requirement as ok, failed, or skipped. It also holds [`build_rootfs`], which
5-//! builds such a rootfs for the tests.
6-
7 use std::fs;1 use std::fs;
8 use std::io;2 use std::io;
9 use std::path::{Path, PathBuf};3 use std::path::{Path, PathBuf};
@@ -17,20 +11,13 @@ use crate::sandbox::SandboxRequest;
17 use crate::sandbox::helper::job_cgroup_base;11 use crate::sandbox::helper::job_cgroup_base;
18 use crate::sandbox::idmap::IdMap;12 use crate::sandbox::idmap::IdMap;
19 13
20-/// The probe job. It prints the seccomp mode of the job, then succeeds.
21 const PROBE_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; true";14 const PROBE_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; true";
22-/// The probe job in subuid mode. It also chowns a file in `/tmp` to 1000:1000 and prints its
23-/// owner, which needs the subordinate range.
24 const PROBE_SUBUID_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; \15 const PROBE_SUBUID_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; \
25 touch /tmp/forge-probe && chown 1000:1000 /tmp/forge-probe \16 touch /tmp/forge-probe && chown 1000:1000 /tmp/forge-probe \
26 && stat -c 'owner %u %g' /tmp/forge-probe; true";17 && stat -c 'owner %u %g' /tmp/forge-probe; true";
27-/// The utilities the probe needs in its rootfs.
28 const PROBE_BINARIES: &[&str] = &["sh", "grep", "touch", "chown", "stat"];18 const PROBE_BINARIES: &[&str] = &["sh", "grep", "touch", "chown", "stat"];
29-/// The controllers the job cgroup needs for `[limits]`.
30 const LIMIT_CONTROLLERS: [&str; 3] = ["cpu", "memory", "pids"];19 const LIMIT_CONTROLLERS: [&str; 3] = ["cpu", "memory", "pids"];
31 20
32-/// Copies `binaries` (looked up in `/usr/bin` and `/bin`) and their shared libraries into `root`,
33-/// at the same absolute paths. It also creates the empty mount points the sandbox needs.
34 pub fn build_rootfs(root: &Path, binaries: &[&str]) -> io::Result<()> {21 pub fn build_rootfs(root: &Path, binaries: &[&str]) -> io::Result<()> {
35 for dir in [22 for dir in [
36 "bin",23 "bin",
@@ -70,7 +57,6 @@ pub fn build_rootfs(root: &Path, binaries: &[&str]) -> io::Result<()> {
70 Ok(())57 Ok(())
71 }58 }
72 59
73-/// The shared libraries `ldd` reports for `binary`, as absolute host paths.
74 fn shared_libs(binary: &Path) -> Vec<PathBuf> {60 fn shared_libs(binary: &Path) -> Vec<PathBuf> {
75 let Ok(out) = std::process::Command::new("ldd").arg(binary).output() else {61 let Ok(out) = std::process::Command::new("ldd").arg(binary).output() else {
76 return Vec::new();62 return Vec::new();
@@ -98,7 +84,6 @@ fn copy_into(root: &Path, host: &Path) -> io::Result<()> {
98 Ok(())84 Ok(())
99 }85 }
100 86
101-/// How one requirement came out.
102 #[derive(Debug, Clone, Copy, PartialEq, Eq)]87 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
103 pub enum Status {88 pub enum Status {
104 Ok,89 Ok,
@@ -106,7 +91,6 @@ pub enum Status {
106 Skip,91 Skip,
107 }92 }
108 93
109-/// One line of the report.
110 #[derive(Debug, Clone, PartialEq, Eq)]94 #[derive(Debug, Clone, PartialEq, Eq)]
111 pub struct Line {95 pub struct Line {
112 pub status: Status,96 pub status: Status,
@@ -140,15 +124,12 @@ impl Line {
140 }124 }
141 }125 }
142 126
143-/// The helper's output and exit status for the probe job.
144 struct Probe {127 struct Probe {
145 status: ExitStatus,128 status: ExitStatus,
146 stdout: String,129 stdout: String,
147 stderr: String,130 stderr: String,
148 }131 }
149 132
150-/// Runs the probe job through the sandbox helper at `helper`, under `map`. `work_dir` must be
151-/// absolute.
152 async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, String> {133 async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, String> {
153 let root = work_dir.join(format!("check-{}", std::process::id()));134 let root = work_dir.join(format!("check-{}", std::process::id()));
154 let rootfs = root.join("rootfs");135 let rootfs = root.join("rootfs");
@@ -204,7 +185,6 @@ async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe,
204 })185 })
205 }186 }
206 187
207-/// The helper's `forge-sandbox: ` lines, without the prefix.
208 fn sandbox_lines(stderr: &str) -> Vec<&str> {188 fn sandbox_lines(stderr: &str) -> Vec<&str> {
209 stderr189 stderr
210 .lines()190 .lines()
@@ -212,8 +192,6 @@ fn sandbox_lines(stderr: &str) -> Vec<&str> {
212 .collect()192 .collect()
213 }193 }
214 194
215-/// The cgroup v2 controllers enabled for job cgroups, read where the helper puts them. Fails when
216-/// that cgroup is not ours to write, as in an SSH session's scope.
217 fn delegated_controllers() -> Result<Vec<String>, String> {195 fn delegated_controllers() -> Result<Vec<String>, String> {
218 let base = job_cgroup_base().map_err(|e| e.to_string())?;196 let base = job_cgroup_base().map_err(|e| e.to_string())?;
219 let dir = Path::new("/sys/fs/cgroup").join(base.strip_prefix("/").unwrap_or(&base));197 let dir = Path::new("/sys/fs/cgroup").join(base.strip_prefix("/").unwrap_or(&base));
@@ -231,7 +209,6 @@ fn delegated_controllers() -> Result<Vec<String>, String> {
231 Ok(enabled.split_whitespace().map(str::to_owned).collect())209 Ok(enabled.split_whitespace().map(str::to_owned).collect())
232 }210 }
233 211
234-/// The runner checks out each job's commit with the host's `git`.
235 async fn git_line() -> Line {212 async fn git_line() -> Line {
236 match Command::new("git").arg("--version").output().await {213 match Command::new("git").arg("--version").output().await {
237 Ok(out) if out.status.success() => Line::ok(214 Ok(out) if out.status.success() => Line::ok(
@@ -243,7 +220,6 @@ async fn git_line() -> Line {
243 }220 }
244 }221 }
245 222
246-/// Builds the report from the probe result. Pure, so the rules can be tested.
247 fn report(probe: Result<&Probe, &str>, controllers: Result<&[String], &str>) -> Vec<Line> {223 fn report(probe: Result<&Probe, &str>, controllers: Result<&[String], &str>) -> Vec<Line> {
248 let mut lines = Vec::new();224 let mut lines = Vec::new();
249 225
@@ -380,8 +356,6 @@ fn report(probe: Result<&Probe, &str>, controllers: Result<&[String], &str>) ->
380 lines356 lines
381 }357 }
382 358
383-/// The subordinate id check, in subuid mode. The probe must have started, and must have chowned
384-/// its file in `/tmp` to 1000:1000, which is container id 1000 and needs the subordinate range.
385 fn ownership_line(probe: &Probe) -> Line {359 fn ownership_line(probe: &Probe) -> Line {
386 const NAME: &str = "subordinate ids";360 const NAME: &str = "subordinate ids";
387 if !probe.stdout.lines().any(|l| l.starts_with("Seccomp:")) {361 if !probe.stdout.lines().any(|l| l.starts_with("Seccomp:")) {
@@ -401,10 +375,6 @@ fn ownership_line(probe: &Probe) -> Line {
401 )375 )
402 }376 }
403 377
404-/// Runs every check and prints one line per requirement. Returns `true` when all pass.
405-///
406-/// `helper` is the `forge-runner` binary, and `work_dir` is where the probe runs. The probe needs
407-/// the same filesystem that jobs will use. `mode` is the `[sandbox] userns` setting.
408 pub async fn run(helper: &Path, work_dir: &Path, mode: UsernsMode) -> bool {378 pub async fn run(helper: &Path, work_dir: &Path, mode: UsernsMode) -> bool {
409 let work_dir = match std::path::absolute(work_dir) {379 let work_dir = match std::path::absolute(work_dir) {
410 Ok(path) => path,380 Ok(path) => path,
crates/forge-runner/src/cli.rsmodified+0 -40
@@ -1,8 +1,3 @@
1-//! The `forge-runner` command line: `register`, `run` and `check`.
2-//!
3-//! The standalone `forge-runner` binary and `forge runner` both call [`main_with_args`], so
4-//! the two behave the same way.
5-
6 use std::ffi::OsString;1 use std::ffi::OsString;
7 use std::path::PathBuf;2 use std::path::PathBuf;
8 use std::process::ExitCode;3 use std::process::ExitCode;
@@ -27,7 +22,6 @@ use crate::sandbox::idmap::IdMap;
27 use crate::selflog;22 use crate::selflog;
28 use crate::update;23 use crate::update;
29 24
30-/// How often unused images are garbage collected, after the one at startup.
31 const GC_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);25 const GC_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
32 26
33 #[derive(Parser)]27 #[derive(Parser)]
@@ -43,58 +37,38 @@ struct Cli {
43 37
44 #[derive(Subcommand)]38 #[derive(Subcommand)]
45 enum Command {39 enum Command {
46- /// Register this machine with a forge and write the runner config (mode 0600).
47 Register {40 Register {
48- /// Forge base URL, for example https://forge.example
49 #[arg(long)]41 #[arg(long)]
50 url: String,42 url: String,
51- /// Registration token shown by the forge admin page.
52 #[arg(long)]43 #[arg(long)]
53 token: String,44 token: String,
54- /// Runner name shown in the forge.
55 #[arg(long)]45 #[arg(long)]
56 name: String,46 name: String,
57- /// Comma-separated runner labels, for example linux,x86_64.
58 #[arg(long, value_delimiter = ',')]47 #[arg(long, value_delimiter = ',')]
59 labels: Vec<String>,48 labels: Vec<String>,
60- /// Where to write the config. Default: ~/.config/forge-runner/runner.toml
61 #[arg(long)]49 #[arg(long)]
62 config: Option<PathBuf>,50 config: Option<PathBuf>,
63- /// Where job workspaces go. Default: ~/.cache/forge-runner/work
64 #[arg(long)]51 #[arg(long)]
65 work_dir: Option<PathBuf>,52 work_dir: Option<PathBuf>,
66 },53 },
67- /// Claim and run jobs until interrupted.
68 Run {54 Run {
69- /// The config file. Default: ~/.config/forge-runner/runner.toml
70 #[arg(long)]55 #[arg(long)]
71 config: Option<PathBuf>,56 config: Option<PathBuf>,
72 },57 },
73- /// Check that this host can run builtin jobs: user namespaces, overlayfs, cgroup limits,
74- /// seccomp and, in subuid mode, subordinate ids. Runs one trivial job through the real sandbox.
75 Check {58 Check {
76- /// Where the probe runs. It should be on the filesystem that jobs use.
77- /// Default: ~/.cache/forge-runner/work
78 #[arg(long)]59 #[arg(long)]
79 work_dir: Option<PathBuf>,60 work_dir: Option<PathBuf>,
80- /// The runner config, for its `[sandbox] userns` setting. Default: the default config
81- /// path, if that file exists, otherwise `auto`.
82 #[arg(long)]61 #[arg(long)]
83 config: Option<PathBuf>,62 config: Option<PathBuf>,
84 },63 },
85 }64 }
86 65
87-/// Runs the `forge-runner` command line. `args` are the arguments after the program name, so
88-/// `register --url ...` and not `forge-runner register --url ...`. `bin_name` is shown in help
89-/// and error messages, for example `forge runner`.
90 pub fn main_with_args<I, T>(bin_name: &str, args: I) -> ExitCode66 pub fn main_with_args<I, T>(bin_name: &str, args: I) -> ExitCode
91 where67 where
92 I: IntoIterator<Item = T>,68 I: IntoIterator<Item = T>,
93 T: Into<OsString>,69 T: Into<OsString>,
94 {70 {
95 let args: Vec<OsString> = args.into_iter().map(Into::into).collect();71 let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
96- // The sandbox helper is single-threaded and must not have a tokio runtime, because
97- // libcontainer forks and clones. Dispatch it before anything else starts.
98 if args.first().is_some_and(is_sandbox_arg) {72 if args.first().is_some_and(is_sandbox_arg) {
99 std::process::exit(hidden_dispatch(&args));73 std::process::exit(hidden_dispatch(&args));
100 }74 }
@@ -142,17 +116,12 @@ where
142 })116 })
143 }117 }
144 118
145-/// Whether this process was started as a hidden sandbox helper: argv[1] is `__sandbox`,
146-/// `__sandbox-rm`, `__sandbox-map` or `__sandbox-unpack`. Callers that have their own runtime or subscriber check
147-/// this first, and then call [`hidden_main`].
148 pub fn is_sandbox_invocation() -> bool {119 pub fn is_sandbox_invocation() -> bool {
149 std::env::args_os()120 std::env::args_os()
150 .nth(1)121 .nth(1)
151 .is_some_and(|arg| is_sandbox_arg(&arg))122 .is_some_and(|arg| is_sandbox_arg(&arg))
152 }123 }
153 124
154-/// Runs the hidden helper named by argv[1]. The helpers are single-threaded and must not start
155-/// a tokio runtime. Returns the process exit code.
156 pub fn hidden_main() -> i32 {125 pub fn hidden_main() -> i32 {
157 let args: Vec<OsString> = std::env::args_os().skip(1).collect();126 let args: Vec<OsString> = std::env::args_os().skip(1).collect();
158 hidden_dispatch(&args)127 hidden_dispatch(&args)
@@ -162,7 +131,6 @@ fn is_sandbox_arg(arg: &OsString) -> bool {
162 arg.as_encoded_bytes().starts_with(b"__sandbox")131 arg.as_encoded_bytes().starts_with(b"__sandbox")
163 }132 }
164 133
165-/// Routes a hidden helper command. `args` start with the command name.
166 fn hidden_dispatch(args: &[OsString]) -> i32 {134 fn hidden_dispatch(args: &[OsString]) -> i32 {
167 match args.first().map(|arg| arg.as_encoded_bytes()) {135 match args.first().map(|arg| arg.as_encoded_bytes()) {
168 Some(b"__sandbox") => crate::sandbox::helper_main(),136 Some(b"__sandbox") => crate::sandbox::helper_main(),
@@ -306,8 +274,6 @@ async fn run(cli: Cli) -> Result<ExitCode, Box<dyn std::error::Error>> {
306 }274 }
307 }275 }
308 276
309-/// The `[sandbox] userns` setting for `check`. An explicit config must exist. Without one, the
310-/// default config is used if it exists, and otherwise the mode is `auto`.
311 fn check_userns_mode(config_path: Option<PathBuf>) -> Result<UsernsMode, config::ConfigError> {277 fn check_userns_mode(config_path: Option<PathBuf>) -> Result<UsernsMode, config::ConfigError> {
312 if let Some(path) = config_path {278 if let Some(path) = config_path {
313 return Ok(config::load(&path)?.sandbox.userns);279 return Ok(config::load(&path)?.sandbox.userns);
@@ -318,8 +284,6 @@ fn check_userns_mode(config_path: Option<PathBuf>) -> Result<UsernsMode, config:
318 }284 }
319 }285 }
320 286
321-/// Garbage collects unused images now and then once a day, until `shutdown` is cancelled. Images
322-/// are removed under `map`, the same as when they were unpacked.
323 fn spawn_image_gc(287 fn spawn_image_gc(
324 root: PathBuf,288 root: PathBuf,
325 keep_days: u32,289 keep_days: u32,
@@ -347,14 +311,10 @@ fn spawn_image_gc(
347 });311 });
348 }312 }
349 313
350-/// `image_max_gb` as bytes.
351 fn gib(gb: u64) -> u64 {314 fn gib(gb: u64) -> u64 {
352 gb.saturating_mul(1024 * 1024 * 1024)315 gb.saturating_mul(1024 * 1024 * 1024)
353 }316 }
354 317
355-/// Applies the admin's startup-time overrides from the forge to `cfg` and reports the effective
356-/// config back for the admin page. Best effort: an older forge, or a forge that cannot be reached,
357-/// leaves `runner.toml` as it is and the runner starts anyway.
358 async fn sync_config_with_forge(cfg: &mut RunnerConfig) {318 async fn sync_config_with_forge(cfg: &mut RunnerConfig) {
359 let client = match crate::client::ForgeClient::new(&cfg.url) {319 let client = match crate::client::ForgeClient::new(&cfg.url) {
360 Ok(client) => client,320 Ok(client) => client,
crates/forge-runner/src/client.rsmodified+0 -52
@@ -1,8 +1,3 @@
1-//! HTTP client for the forge runner API (contract section 4).
2-//!
3-//! Runner calls (register, claim) authenticate with the runner secret. Job calls (logs,
4-//! heartbeat, artifacts, finish) authenticate with the per-job token.
5-
6 use std::path::Path;1 use std::path::Path;
7 use std::time::Duration;2 use std::time::Duration;
8 3
@@ -19,7 +14,6 @@ use serde::de::DeserializeOwned;
19 use sha2::{Digest, Sha256};14 use sha2::{Digest, Sha256};
20 use tokio::io::AsyncWriteExt;15 use tokio::io::AsyncWriteExt;
21 16
22-/// The claim long-poll is 25s on the forge side, so 35s leaves room for the response.
23 pub const CLAIM_TIMEOUT: Duration = Duration::from_secs(35);17 pub const CLAIM_TIMEOUT: Duration = Duration::from_secs(35);
24 const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);18 const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
25 const LOG_TIMEOUT: Duration = Duration::from_secs(60);19 const LOG_TIMEOUT: Duration = Duration::from_secs(60);
@@ -27,19 +21,13 @@ const ARTIFACT_TIMEOUT: Duration = Duration::from_secs(60 * 60);
27 const BINARY_TIMEOUT: Duration = Duration::from_secs(10 * 60);21 const BINARY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
28 const HEADER_LOG_OFFSET: &str = "X-Forge-Log-Offset";22 const HEADER_LOG_OFFSET: &str = "X-Forge-Log-Offset";
29 const HEADER_LOG_SIZE: &str = "X-Forge-Log-Size";23 const HEADER_LOG_SIZE: &str = "X-Forge-Log-Size";
30-/// Sent on every claim: `<ARCH>-<OS>` of this runner, for example `x86_64-linux`.
31 const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target";24 const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target";
32-/// On a claim response: the sha256 (hex) of the forge's own binary, if the forge advertises one.
33 const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256";25 const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256";
34-/// `GET`: the forge's binary, for a runner that is updating itself.
35 const BINARY_PATH: &str = "/api/v1/ci/runners/binary";26 const BINARY_PATH: &str = "/api/v1/ci/runners/binary";
36 const CONFIG_PATH: &str = "/api/v1/ci/runners/config";27 const CONFIG_PATH: &str = "/api/v1/ci/runners/config";
37-/// `POST`: lines of the runner's own log, see [`crate::selflog`].
38 const RUNNER_LOG_PATH: &str = "/api/v1/ci/runners/log";28 const RUNNER_LOG_PATH: &str = "/api/v1/ci/runners/log";
39-/// `POST`: host samples for the runner's graphs, see [`crate::metrics`].
40 const RUNNER_METRICS_PATH: &str = "/api/v1/ci/runners/metrics";29 const RUNNER_METRICS_PATH: &str = "/api/v1/ci/runners/metrics";
41 30
42-/// Errors from talking to the forge.
43 #[derive(Debug, thiserror::Error)]31 #[derive(Debug, thiserror::Error)]
44 pub enum ClientError {32 pub enum ClientError {
45 #[error("http: {0}")]33 #[error("http: {0}")]
@@ -52,43 +40,29 @@ pub enum ClientError {
52 Protocol(String),40 Protocol(String),
53 }41 }
54 42
55-/// The forge's answer to a log chunk.
56 #[derive(Clone, Copy, Debug, PartialEq, Eq)]43 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
57 pub enum LogAck {44 pub enum LogAck {
58- /// The chunk was stored (or was already stored, which is an idempotent retry).
59 Accepted,45 Accepted,
60- /// The forge holds a different number of bytes. The runner must continue from this size.
61 Resync(u64),46 Resync(u64),
62 }47 }
63 48
64-/// The forge's answer to a claim.
65 #[derive(Clone, Debug)]49 #[derive(Clone, Debug)]
66 pub struct ClaimReply {50 pub struct ClaimReply {
67- /// The job assigned to this runner, or `None` when there is nothing to run (204).
68 pub job: Option<JobAssignment>,51 pub job: Option<JobAssignment>,
69- /// The sha256 (lowercase hex) of the forge's binary, when the response advertises one.
70 pub binary_sha256: Option<String>,52 pub binary_sha256: Option<String>,
71- /// The concurrency an admin set in the web UI. `None` means no override.
72 pub concurrency: Option<u32>,53 pub concurrency: Option<u32>,
73- /// A restart an admin asked for, from the `Forge-Runner-Restart` header.
74 pub restart: Option<RestartMode>,54 pub restart: Option<RestartMode>,
75- /// The memory budget an admin set (`6g`). `None` means no override.
76 pub memory_budget: Option<String>,55 pub memory_budget: Option<String>,
77- /// The default reservation an admin set (`1g`). `None` means no override.
78 pub reserve_memory: Option<String>,56 pub reserve_memory: Option<String>,
79 }57 }
80 58
81-/// What a claim tells the forge about the runner's memory.
82 #[derive(Clone, Copy, Debug, PartialEq, Eq)]59 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
83 pub struct MemoryClaim {60 pub struct MemoryClaim {
84- /// Budget minus running reservations: the forge hands out only a job that fits.
85 pub free: u64,61 pub free: u64,
86 pub budget: u64,62 pub budget: u64,
87- /// What a job without `memory` reserves.
88 pub reserve: u64,63 pub reserve: u64,
89 }64 }
90 65
91-/// A client for one forge base URL.
92 #[derive(Clone, Debug)]66 #[derive(Clone, Debug)]
93 pub struct ForgeClient {67 pub struct ForgeClient {
94 http: reqwest::Client,68 http: reqwest::Client,
@@ -96,7 +70,6 @@ pub struct ForgeClient {
96 }70 }
97 71
98 impl ForgeClient {72 impl ForgeClient {
99- /// Builds a client for `base_url`, for example `https://forge.example`.
100 pub fn new(base_url: &str) -> Result<Self, ClientError> {73 pub fn new(base_url: &str) -> Result<Self, ClientError> {
101 let http = reqwest::Client::builder()74 let http = reqwest::Client::builder()
102 .user_agent(concat!("forge-runner/", env!("CARGO_PKG_VERSION")))75 .user_agent(concat!("forge-runner/", env!("CARGO_PKG_VERSION")))
@@ -112,7 +85,6 @@ impl ForgeClient {
112 format!("{}{}", self.base, path)85 format!("{}{}", self.base, path)
113 }86 }
114 87
115- /// `POST /api/v1/ci/runners/register`.
116 pub async fn register(&self, req: &RegisterRequest) -> Result<RegisterResponse, ClientError> {88 pub async fn register(&self, req: &RegisterRequest) -> Result<RegisterResponse, ClientError> {
117 let resp = self89 let resp = self
118 .http90 .http
@@ -124,7 +96,6 @@ impl ForgeClient {
124 json_or_error(resp).await96 json_or_error(resp).await
125 }97 }
126 98
127- /// `POST /api/v1/ci/runners/claim`. A 204 means nothing to run, and the reply has no job.
128 pub async fn claim(99 pub async fn claim(
129 &self,100 &self,
130 runner_secret: &str,101 runner_secret: &str,
@@ -133,8 +104,6 @@ impl ForgeClient {
133 self.claim_with(runner_secret, labels, None, None).await104 self.claim_with(runner_secret, labels, None, None).await
134 }105 }
135 106
136- /// Like [`ForgeClient::claim`], and also reports the runner's live `concurrency` and its host
137- /// facts (version, CPUs, memory) for the forge's admin page.
138 pub async fn claim_with(107 pub async fn claim_with(
139 &self,108 &self,
140 runner_secret: &str,109 runner_secret: &str,
@@ -190,7 +159,6 @@ impl ForgeClient {
190 }159 }
191 }160 }
192 161
193- /// `GET /api/v1/ci/runners/config`: the overrides an admin set for this runner.
194 pub async fn get_config(162 pub async fn get_config(
195 &self,163 &self,
196 runner_secret: &str,164 runner_secret: &str,
@@ -205,7 +173,6 @@ impl ForgeClient {
205 json_or_error(resp).await173 json_or_error(resp).await
206 }174 }
207 175
208- /// `PUT /api/v1/ci/runners/config`: reports the runner's effective config (secrets redacted).
209 pub async fn put_config(176 pub async fn put_config(
210 &self,177 &self,
211 runner_secret: &str,178 runner_secret: &str,
@@ -222,8 +189,6 @@ impl ForgeClient {
222 json_or_error(resp).await189 json_or_error(resp).await
223 }190 }
224 191
225- /// `POST /api/v1/ci/runners/log`: ships a batch of the runner's own log. Returns the forge's
226- /// ack, the number of the next line it wants.
227 pub async fn post_runner_log(192 pub async fn post_runner_log(
228 &self,193 &self,
229 runner_secret: &str,194 runner_secret: &str,
@@ -240,7 +205,6 @@ impl ForgeClient {
240 json_or_error(resp).await205 json_or_error(resp).await
241 }206 }
242 207
243- /// `POST /api/v1/ci/runners/metrics`: ships host samples. Answered with 204.
244 pub async fn post_runner_metrics(208 pub async fn post_runner_metrics(
245 &self,209 &self,
246 runner_secret: &str,210 runner_secret: &str,
@@ -257,9 +221,6 @@ impl ForgeClient {
257 empty_or_error(resp).await221 empty_or_error(resp).await
258 }222 }
259 223
260- /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the
261- /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised
262- /// value and syncs the file.
263 pub async fn download_binary(224 pub async fn download_binary(
264 &self,225 &self,
265 runner_secret: &str,226 runner_secret: &str,
@@ -285,7 +246,6 @@ impl ForgeClient {
285 Ok(hex::encode(hasher.finalize()))246 Ok(hex::encode(hasher.finalize()))
286 }247 }
287 248
288- /// `POST /api/v1/ci/jobs/{id}/logs` with the byte offset of `body` in the job log.
289 pub async fn post_logs(249 pub async fn post_logs(
290 &self,250 &self,
291 job_id: &str,251 job_id: &str,
@@ -320,7 +280,6 @@ impl ForgeClient {
320 }280 }
321 }281 }
322 282
323- /// `POST /api/v1/ci/jobs/{id}/heartbeat`.
324 pub async fn heartbeat(283 pub async fn heartbeat(
325 &self,284 &self,
326 job_id: &str,285 job_id: &str,
@@ -329,7 +288,6 @@ impl ForgeClient {
329 self.heartbeat_with(job_id, job_token, None).await288 self.heartbeat_with(job_id, job_token, None).await
330 }289 }
331 290
332- /// Like [`ForgeClient::heartbeat`], and also tells the forge the runner's live `concurrency`.
333 pub async fn heartbeat_with(291 pub async fn heartbeat_with(
334 &self,292 &self,
335 job_id: &str,293 job_id: &str,
@@ -348,7 +306,6 @@ impl ForgeClient {
348 json_or_error(req.send().await?).await306 json_or_error(req.send().await?).await
349 }307 }
350 308
351- /// `PUT /api/v1/ci/jobs/{id}/artifacts/{name}`, streaming the file from disk.
352 pub async fn upload_artifact(309 pub async fn upload_artifact(
353 &self,310 &self,
354 job_id: &str,311 job_id: &str,
@@ -371,7 +328,6 @@ impl ForgeClient {
371 empty_or_error(resp).await328 empty_or_error(resp).await
372 }329 }
373 330
374- /// `POST /api/v1/ci/jobs/{id}/finish`.
375 pub async fn finish(331 pub async fn finish(
376 &self,332 &self,
377 job_id: &str,333 job_id: &str,
@@ -389,7 +345,6 @@ impl ForgeClient {
389 empty_or_error(resp).await345 empty_or_error(resp).await
390 }346 }
391 347
392- /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place.
393 pub async fn requeue(348 pub async fn requeue(
394 &self,349 &self,
395 job_id: &str,350 job_id: &str,
@@ -410,7 +365,6 @@ impl ForgeClient {
410 }365 }
411 }366 }
412 367
413-/// The `Forge-Binary-Sha256` header, trimmed and lowercased. An empty value counts as absent.
414 fn advertised_sha256(headers: &HeaderMap) -> Option<String> {368 fn advertised_sha256(headers: &HeaderMap) -> Option<String> {
415 headers369 headers
416 .get(HEADER_BINARY_SHA256)?370 .get(HEADER_BINARY_SHA256)?
@@ -420,7 +374,6 @@ fn advertised_sha256(headers: &HeaderMap) -> Option<String> {
420 .filter(|v| !v.is_empty())374 .filter(|v| !v.is_empty())
421 }375 }
422 376
423-/// The `Forge-Runner-Concurrency` header, when it holds a number.
424 fn advertised_concurrency(headers: &HeaderMap) -> Option<u32> {377 fn advertised_concurrency(headers: &HeaderMap) -> Option<u32> {
425 headers378 headers
426 .get(CONCURRENCY_HEADER)?379 .get(CONCURRENCY_HEADER)?
@@ -431,12 +384,10 @@ fn advertised_concurrency(headers: &HeaderMap) -> Option<u32> {
431 .ok()384 .ok()
432 }385 }
433 386
434-/// The `Forge-Runner-Restart` header, when it holds a mode this runner knows.
435 fn advertised_restart(headers: &HeaderMap) -> Option<RestartMode> {387 fn advertised_restart(headers: &HeaderMap) -> Option<RestartMode> {
436 RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?)388 RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?)
437 }389 }
438 390
439-/// Cheap facts about the host that help an admin size the runner's concurrency.
440 struct HostFacts {391 struct HostFacts {
441 cpus: Option<u32>,392 cpus: Option<u32>,
442 memory_bytes: Option<u64>,393 memory_bytes: Option<u64>,
@@ -482,9 +433,6 @@ async fn status_error(resp: reqwest::Response) -> ClientError {
482 ClientError::Status { status, body }433 ClientError::Status { status, body }
483 }434 }
484 435
485-/// The part of an error body worth a log line: an HTML error page (a proxy's or the forge's own 503
486-/// page) says no more than the status does, so it is dropped; any other text is folded onto one line
487-/// and cut at 512 characters.
488 fn short_body(text: &str) -> String {436 fn short_body(text: &str) -> String {
489 let text = text.trim_start();437 let text = text.trim_start();
490 if text.starts_with('<') {438 if text.starts_with('<') {
crates/forge-runner/src/config.rsmodified+0 -52
@@ -1,5 +1,3 @@
1-//! The runner's `runner.toml`: the forge URL, the runner identity and secret, and local limits.
2-
3 use std::collections::BTreeMap;1 use std::collections::BTreeMap;
4 use std::fmt;2 use std::fmt;
5 use std::fs::OpenOptions;3 use std::fs::OpenOptions;
@@ -11,7 +9,6 @@ use serde::{Deserialize, Serialize};
11 9
12 pub use crate::sandbox::idmap::UsernsMode;10 pub use crate::sandbox::idmap::UsernsMode;
13 11
14-/// Errors from reading or writing the config file.
15 #[derive(Debug, thiserror::Error)]12 #[derive(Debug, thiserror::Error)]
16 pub enum ConfigError {13 pub enum ConfigError {
17 #[error("config file {path}: {source}")]14 #[error("config file {path}: {source}")]
@@ -30,37 +27,24 @@ pub enum ConfigError {
30 NoHome,27 NoHome,
31 }28 }
32 29
33-/// Per-job resource limits, applied through the job's cgroup.
34 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]30 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35 #[serde(deny_unknown_fields)]31 #[serde(deny_unknown_fields)]
36 pub struct Limits {32 pub struct Limits {
37 pub memory: String,33 pub memory: String,
38 pub cpus: String,34 pub cpus: String,
39 pub pids: u32,35 pub pids: u32,
40- /// The cap on the unpacked size of one image, in GB. Used by the builtin executor.
41 #[serde(default = "default_image_max_gb")]36 #[serde(default = "default_image_max_gb")]
42 pub image_max_gb: u64,37 pub image_max_gb: u64,
43- /// The disk one job may fill, in GB: its workspace, its `/tmp` and what it writes over the
44- /// image. Past it the job is stopped and fails. 0 means no cap. Used by the builtin executor.
45 #[serde(default = "default_job_disk_gb")]38 #[serde(default = "default_job_disk_gb")]
46 pub job_disk_gb: u64,39 pub job_disk_gb: u64,
47- /// What a job that declares no `memory` reserves when it is admitted, and the floor for its
48- /// cgroup limit. Live: an admin can change it from the forge without a restart.
49 #[serde(default = "default_reserve_memory")]40 #[serde(default = "default_reserve_memory")]
50 pub reserve_memory: String,41 pub reserve_memory: String,
51- /// The memory all running jobs may reserve together, like `6g`. Absent or `auto` means the
52- /// host's MemTotal minus the headroom. Live, like `reserve_memory`.
53 #[serde(default, skip_serializing_if = "Option::is_none")]42 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub memory_budget: Option<String>,43 pub memory_budget: Option<String>,
55- /// Memory kept for the host in `auto` mode, as a size. The larger of this and 10% of MemTotal
56- /// is kept free.
57 #[serde(default = "default_memory_headroom")]44 #[serde(default = "default_memory_headroom")]
58 pub memory_headroom: String,45 pub memory_headroom: String,
59- /// Percent of the host's swap that counts toward the `auto` budget. 0 means swap is ignored.
60 #[serde(default)]46 #[serde(default)]
61 pub budget_swap_percent: u32,47 pub budget_swap_percent: u32,
62- /// Swap a job may use on top of `memory`, in bytes. Set per job by the runner, never read
63- /// from `runner.toml`.
64 #[serde(skip)]48 #[serde(skip)]
65 pub swap: u64,49 pub swap: u64,
66 }50 }
@@ -91,10 +75,6 @@ impl Default for Limits {
91 }75 }
92 76
93 impl Limits {77 impl Limits {
94- /// The limits for one job: `memory` becomes the cgroup limit of that job, in bytes. A job
95- /// that declared `memory` gets it plus a little slack, so the job is OOM-killed in its own
96- /// cgroup and not by the host. A job that did not gets the larger of `limits.memory` and the
97- /// default reservation, so it never runs under what the runner reserved for it.
98 pub fn for_job(&self, declared: Option<u64>) -> Limits {78 pub fn for_job(&self, declared: Option<u64>) -> Limits {
99 let mut limits = self.clone();79 let mut limits = self.clone();
100 let configured = forge_ci::size::parse_size(&self.memory);80 let configured = forge_ci::size::parse_size(&self.memory);
@@ -107,9 +87,6 @@ impl Limits {
107 limits87 limits
108 }88 }
109 89
110- /// [`Limits::for_job`] for the builtin executor, where every job sits in the runner's box: a
111- /// job without `memory` may use the whole budget (docs/ci.md, Memory), never less than the
112- /// default reservation. The box and the pressure controller keep jobs together inside it.
113 pub fn for_builtin_job(&self, declared: Option<u64>, budget: Option<u64>, swap: u64) -> Limits {90 pub fn for_builtin_job(&self, declared: Option<u64>, budget: Option<u64>, swap: u64) -> Limits {
114 match (declared, budget) {91 match (declared, budget) {
115 (None, Some(budget)) => {92 (None, Some(budget)) => {
@@ -123,8 +100,6 @@ impl Limits {
123 }100 }
124 }101 }
125 102
126- /// The cgroup `memory.max` of a job in bytes, see [`Limits::for_job`]. `None` when
127- /// `limits.memory` does not parse, which the sandbox reports itself.
128 pub fn job_memory_limit(&self, declared: Option<u64>) -> Option<u64> {103 pub fn job_memory_limit(&self, declared: Option<u64>) -> Option<u64> {
129 if let Some(declared) = declared {104 if let Some(declared) = declared {
130 return Some(declared.saturating_add(memory_slack(declared)));105 return Some(declared.saturating_add(memory_slack(declared)));
@@ -135,13 +110,10 @@ impl Limits {
135 }110 }
136 }111 }
137 112
138-/// Room above a declared `memory` before the job's cgroup kills it: 1/16, at least 256 MiB.
139 pub fn memory_slack(declared: u64) -> u64 {113 pub fn memory_slack(declared: u64) -> u64 {
140 (declared / 16).max(256 << 20)114 (declared / 16).max(256 << 20)
141 }115 }
142 116
143-/// Which executor runs jobs. `builtin` needs no external tool. `podman` runs them with rootless
144-/// podman.
145 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]117 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
146 #[serde(rename_all = "lowercase")]118 #[serde(rename_all = "lowercase")]
147 pub enum ExecutorKind {119 pub enum ExecutorKind {
@@ -150,7 +122,6 @@ pub enum ExecutorKind {
150 Podman,122 Podman,
151 }123 }
152 124
153-/// The `[images]` table: how long unused images are kept.
154 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]125 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
155 #[serde(deny_unknown_fields)]126 #[serde(deny_unknown_fields)]
156 pub struct ImagesConfig {127 pub struct ImagesConfig {
@@ -166,7 +137,6 @@ impl Default for ImagesConfig {
166 }137 }
167 }138 }
168 139
169-/// The `[sandbox]` table: how job ids are mapped. See [`UsernsMode`].
170 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]140 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
171 #[serde(deny_unknown_fields)]141 #[serde(deny_unknown_fields)]
172 pub struct SandboxConfig {142 pub struct SandboxConfig {
@@ -174,8 +144,6 @@ pub struct SandboxConfig {
174 pub userns: UsernsMode,144 pub userns: UsernsMode,
175 }145 }
176 146
177-/// A `[[registry]]` login, matched to an image by its registry host. The password is only in the
178-/// 0600 runner.toml and is never printed.
179 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]147 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
180 #[serde(deny_unknown_fields)]148 #[serde(deny_unknown_fields)]
181 pub struct RegistryConfig {149 pub struct RegistryConfig {
@@ -194,8 +162,6 @@ impl fmt::Debug for RegistryConfig {
194 }162 }
195 }163 }
196 164
197-/// The contents of `runner.toml`. The file is written with mode 0600 because it holds the
198-/// runner secret and registry passwords.
199 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]165 #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
200 #[serde(deny_unknown_fields)]166 #[serde(deny_unknown_fields)]
201 pub struct RunnerConfig {167 pub struct RunnerConfig {
@@ -218,12 +184,8 @@ pub struct RunnerConfig {
218 pub sandbox: SandboxConfig,184 pub sandbox: SandboxConfig,
219 #[serde(default, rename = "registry")]185 #[serde(default, rename = "registry")]
220 pub registries: Vec<RegistryConfig>,186 pub registries: Vec<RegistryConfig>,
221- /// When true (the default), an idle runner replaces itself with the forge's binary when the
222- /// forge advertises a different one on the claim response. The runner then exits with code
223- /// 75 and systemd restarts it. Set `auto_update = false` to pin the binary by hand.
224 #[serde(default = "default_auto_update")]187 #[serde(default = "default_auto_update")]
225 pub auto_update: bool,188 pub auto_update: bool,
226- /// The cap on all build caches together, in GiB. Zero turns the cache off. See `cache`.
227 #[serde(default = "default_cache_max_gib")]189 #[serde(default = "default_cache_max_gib")]
228 pub cache_max_gib: u64,190 pub cache_max_gib: u64,
229 }191 }
@@ -240,12 +202,10 @@ fn default_keep_days() -> u32 {
240 7202 7
241 }203 }
242 204
243-/// The default cap on all build caches together, in GiB.
244 pub fn default_cache_max_gib() -> u64 {205 pub fn default_cache_max_gib() -> u64 {
245 20206 20
246 }207 }
247 208
248-/// The default cap on one unpacked image, in GB.
249 pub fn default_image_max_gb() -> u64 {209 pub fn default_image_max_gb() -> u64 {
250 20210 20
251 }211 }
@@ -275,7 +235,6 @@ impl fmt::Debug for RunnerConfig {
275 }235 }
276 236
277 impl RunnerConfig {237 impl RunnerConfig {
278- /// Checks the values that the runner cannot run without.
279 pub fn validate(&self) -> Result<(), ConfigError> {238 pub fn validate(&self) -> Result<(), ConfigError> {
280 if !(self.url.starts_with("https://") || self.url.starts_with("http://")) {239 if !(self.url.starts_with("https://") || self.url.starts_with("http://")) {
281 return Err(ConfigError::Invalid(240 return Err(ConfigError::Invalid(
@@ -311,9 +270,6 @@ impl RunnerConfig {
311 Ok(())270 Ok(())
312 }271 }
313 272
314- /// The effective config as flat JSON by dotted key, for the forge's admin page. The runner
315- /// secret and registry passwords are never included: the secret shows as `<redacted>` and a
316- /// registry shows only as `host (username)`.
317 pub fn report(&self) -> BTreeMap<String, serde_json::Value> {273 pub fn report(&self) -> BTreeMap<String, serde_json::Value> {
318 use serde_json::json;274 use serde_json::json;
319 let mut m = BTreeMap::new();275 let mut m = BTreeMap::new();
@@ -365,10 +321,6 @@ impl RunnerConfig {
365 m321 m
366 }322 }
367 323
368- /// Applies the admin's overrides from the forge to this in-memory config, for the fields that
369- /// are read at startup. `runner.toml` on disk is not touched. A value that does not fit is
370- /// skipped. Returns one line per field that changed. `concurrency` and `labels` are live and
371- /// handled elsewhere, and fields that are not listed here are ignored.
372 pub fn apply_overrides(324 pub fn apply_overrides(
373 &mut self,325 &mut self,
374 overrides: &BTreeMap<String, serde_json::Value>,326 overrides: &BTreeMap<String, serde_json::Value>,
@@ -468,17 +420,14 @@ fn home_join(rel: &str) -> Result<PathBuf, ConfigError> {
468 Ok(PathBuf::from(home).join(rel))420 Ok(PathBuf::from(home).join(rel))
469 }421 }
470 422
471-/// The default config path: `$HOME/.config/forge-runner/runner.toml`.
472 pub fn default_config_path() -> Result<PathBuf, ConfigError> {423 pub fn default_config_path() -> Result<PathBuf, ConfigError> {
473 home_join(".config/forge-runner/runner.toml")424 home_join(".config/forge-runner/runner.toml")
474 }425 }
475 426
476-/// The default work directory: `$HOME/.cache/forge-runner/work`.
477 pub fn default_work_dir() -> Result<PathBuf, ConfigError> {427 pub fn default_work_dir() -> Result<PathBuf, ConfigError> {
478 home_join(".cache/forge-runner/work")428 home_join(".cache/forge-runner/work")
479 }429 }
480 430
481-/// Reads and validates the config file.
482 pub fn load(path: &Path) -> Result<RunnerConfig, ConfigError> {431 pub fn load(path: &Path) -> Result<RunnerConfig, ConfigError> {
483 let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Io {432 let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Io {
484 path: path.to_owned(),433 path: path.to_owned(),
@@ -489,7 +438,6 @@ pub fn load(path: &Path) -> Result<RunnerConfig, ConfigError> {
489 Ok(config)438 Ok(config)
490 }439 }
491 440
492-/// Writes the config file with mode 0600, creating parent directories as needed.
493 pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> {441 pub fn save(path: &Path, config: &RunnerConfig) -> Result<(), ConfigError> {
494 config.validate()?;442 config.validate()?;
495 let io_err = |source| ConfigError::Io {443 let io_err = |source| ConfigError::Io {
crates/forge-runner/src/disk.rsmodified+0 -13
@@ -1,9 +1,3 @@
1-//! The disk cap of a builtin job (`limits.job_disk_gb`).
2-//!
3-//! A rootless runner has no quotas, so the runner measures what the job wrote every few seconds
4-//! and stops it once that passes the cap. A job can overshoot by what it writes between two
5-//! checks. In subuid mode a dir the job made unreadable to the runner is not counted.
6-
7 use std::collections::HashSet;1 use std::collections::HashSet;
8 use std::fs;2 use std::fs;
9 use std::os::unix::fs::MetadataExt;3 use std::os::unix::fs::MetadataExt;
@@ -14,13 +8,8 @@ use std::time::{Duration, Instant};
14 8
15 use tokio_util::sync::CancellationToken;9 use tokio_util::sync::CancellationToken;
16 10
17-/// How often the job's disk use is measured, at most. A measurement that takes long (a huge tree)
18-/// spaces the next one out to four times its own length, so the walk stays a small share of the
19-/// runner's time.
20 const INTERVAL: Duration = Duration::from_secs(2);11 const INTERVAL: Duration = Duration::from_secs(2);
21 12
22-/// The bytes allocated under `roots`. Symlinks are not followed, and a file with several hard
23-/// links counts once. Entries that can't be read are skipped.
24 pub fn usage(roots: &[PathBuf]) -> u64 {13 pub fn usage(roots: &[PathBuf]) -> u64 {
25 let mut seen = HashSet::new();14 let mut seen = HashSet::new();
26 let mut total = 0u64;15 let mut total = 0u64;
@@ -42,8 +31,6 @@ pub fn usage(roots: &[PathBuf]) -> u64 {
42 total31 total
43 }32 }
44 33
45-/// Measures `roots` about every [`INTERVAL`] until it passes `cap` bytes, then sets `over` and cancels
46-/// `job`. Runs until it fires or is aborted.
47 pub async fn watch(roots: Vec<PathBuf>, cap: u64, job: CancellationToken, over: Arc<AtomicBool>) {34 pub async fn watch(roots: Vec<PathBuf>, cap: u64, job: CancellationToken, over: Arc<AtomicBool>) {
48 let roots = Arc::new(roots);35 let roots = Arc::new(roots);
49 let mut pause = INTERVAL;36 let mut pause = INTERVAL;
crates/forge-runner/src/lib.rsmodified+0 -5
@@ -1,8 +1,3 @@
1-//! The forge CI runner: claims jobs from a forge over HTTPS and runs them in a rootless sandbox
2-//! (builtin) or rootless podman.
3-//!
4-//! The binaries are thin wrappers over [`cli`] and these modules.
5-
6 pub(crate) mod artifacts;1 pub(crate) mod artifacts;
7 pub(crate) mod cache;2 pub(crate) mod cache;
8 pub mod check;3 pub mod check;
crates/forge-runner/src/limiter.rsmodified+0 -21
@@ -1,29 +1,19 @@
1-//! The runner's live job concurrency. A tokio semaphore holds one permit per job slot. The limit
2-//! can change while jobs run: growing adds permits, shrinking takes back the idle ones at once and
3-//! the rest as running jobs finish. A running job is never killed to make room.
4-
5 use std::sync::{Arc, Mutex, PoisonError};1 use std::sync::{Arc, Mutex, PoisonError};
6 2
7 use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY};3 use forge_ci::proto::{MAX_CONCURRENCY, MIN_CONCURRENCY};
8 use tokio::sync::{OwnedSemaphorePermit, Semaphore};4 use tokio::sync::{OwnedSemaphorePermit, Semaphore};
9 5
10-/// A resizable job limit. Cheap to share: clone the `Arc`.
11 pub struct Limiter {6 pub struct Limiter {
12 semaphore: Arc<Semaphore>,7 semaphore: Arc<Semaphore>,
13- /// The value from `runner.toml`, used when the forge has no override.
14 base: usize,8 base: usize,
15 state: Mutex<State>,9 state: Mutex<State>,
16 }10 }
17 11
18 struct State {12 struct State {
19- /// The limit now.
20 current: usize,13 current: usize,
21- /// Permits still to be taken back after a shrink, because jobs hold them. Each is forgotten
22- /// instead of released when the job that holds one finishes.
23 debt: usize,14 debt: usize,
24 }15 }
25 16
26-/// A job slot. Dropping it frees the slot, or retires it when the limit was lowered.
27 pub struct Slot {17 pub struct Slot {
28 permit: Option<OwnedSemaphorePermit>,18 permit: Option<OwnedSemaphorePermit>,
29 limiter: Arc<Limiter>,19 limiter: Arc<Limiter>,
@@ -37,13 +27,11 @@ impl Drop for Slot {
37 }27 }
38 }28 }
39 29
40-/// Clamps a requested concurrency to the range the forge accepts.
41 pub fn clamp(n: usize) -> usize {30 pub fn clamp(n: usize) -> usize {
42 n.clamp(MIN_CONCURRENCY as usize, MAX_CONCURRENCY as usize)31 n.clamp(MIN_CONCURRENCY as usize, MAX_CONCURRENCY as usize)
43 }32 }
44 33
45 impl Limiter {34 impl Limiter {
46- /// A limiter starting at `base`, which is also the fallback when the forge sends no override.
47 pub fn new(base: usize) -> Arc<Self> {35 pub fn new(base: usize) -> Arc<Self> {
48 let base = clamp(base);36 let base = clamp(base);
49 Arc::new(Self {37 Arc::new(Self {
@@ -56,12 +44,10 @@ impl Limiter {
56 })44 })
57 }45 }
58 46
59- /// The limit now.
60 pub fn current(&self) -> usize {47 pub fn current(&self) -> usize {
61 self.lock().current48 self.lock().current
62 }49 }
63 50
64- /// Job slots free right now. Zero means every slot is taken by a running job.
65 pub fn free_slots(&self) -> usize {51 pub fn free_slots(&self) -> usize {
66 self.semaphore.available_permits()52 self.semaphore.available_permits()
67 }53 }
@@ -70,7 +56,6 @@ impl Limiter {
70 self.state.lock().unwrap_or_else(PoisonError::into_inner)56 self.state.lock().unwrap_or_else(PoisonError::into_inner)
71 }57 }
72 58
73- /// Waits for a free slot. `Err` when the semaphore is closed, which only happens at teardown.
74 pub async fn acquire(self: &Arc<Self>) -> Result<Slot, tokio::sync::AcquireError> {59 pub async fn acquire(self: &Arc<Self>) -> Result<Slot, tokio::sync::AcquireError> {
75 let permit = self.semaphore.clone().acquire_owned().await?;60 let permit = self.semaphore.clone().acquire_owned().await?;
76 Ok(Slot {61 Ok(Slot {
@@ -79,8 +64,6 @@ impl Limiter {
79 })64 })
80 }65 }
81 66
82- /// Applies what the forge asked for: `Some(n)` is an override, `None` means no override and
83- /// brings back the `runner.toml` value. Returns `(old, new)` when the limit changed.
84 pub fn apply(&self, desired: Option<u32>) -> Option<(usize, usize)> {67 pub fn apply(&self, desired: Option<u32>) -> Option<(usize, usize)> {
85 let target = desired.map_or(self.base, |n| clamp(n as usize));68 let target = desired.map_or(self.base, |n| clamp(n as usize));
86 let mut state = self.lock();69 let mut state = self.lock();
@@ -90,7 +73,6 @@ impl Limiter {
90 }73 }
91 if target > old {74 if target > old {
92 let mut grow = target - old;75 let mut grow = target - old;
93- // Permits owed from an earlier shrink are simply kept.
94 let cancel = grow.min(state.debt);76 let cancel = grow.min(state.debt);
95 state.debt -= cancel;77 state.debt -= cancel;
96 grow -= cancel;78 grow -= cancel;
@@ -104,7 +86,6 @@ impl Limiter {
104 Some((old, target))86 Some((old, target))
105 }87 }
106 88
107- /// Like [`Limiter::apply`], and logs one line when the limit changes.
108 pub fn apply_logged(&self, desired: Option<u32>) {89 pub fn apply_logged(&self, desired: Option<u32>) {
109 if let Some((old, new)) = self.apply(desired) {90 if let Some((old, new)) = self.apply(desired) {
110 let from = if desired.is_some() {91 let from = if desired.is_some() {
@@ -122,7 +103,6 @@ impl Limiter {
122 state.debt -= 1;103 state.debt -= 1;
123 permit.forget();104 permit.forget();
124 }105 }
125- // Otherwise the permit drops here and the slot is free again.
126 }106 }
127 }107 }
128 108
@@ -140,7 +120,6 @@ mod tests {
140 let c = limiter.acquire().await.unwrap();120 let c = limiter.acquire().await.unwrap();
141 assert_eq!(limiter.semaphore.available_permits(), 0);121 assert_eq!(limiter.semaphore.available_permits(), 0);
142 122
143- // Shrink to 1 while all 3 slots are busy: nothing is killed, the slots retire on finish.
144 assert_eq!(limiter.apply(Some(1)), Some((3, 1)));123 assert_eq!(limiter.apply(Some(1)), Some((3, 1)));
145 assert_eq!(limiter.current(), 1);124 assert_eq!(limiter.current(), 1);
146 drop(b);125 drop(b);
crates/forge-runner/src/logs.rsmodified+0 -53
@@ -1,5 +1,3 @@
1-//! Job log shipping: merge the job's output, mask secrets, batch it, and POST it with byte offsets.
2-
3 use std::collections::VecDeque;1 use std::collections::VecDeque;
4 use std::time::Duration;2 use std::time::Duration;
5 3
@@ -10,14 +8,10 @@ use tokio::time::{Instant, MissedTickBehavior};
10 8
11 use crate::client::{ClientError, ForgeClient, LogAck};9 use crate::client::{ClientError, ForgeClient, LogAck};
12 10
13-/// A batch never grows past this many bytes. The forge accepts chunks up to 1 MiB.
14 pub const MAX_BATCH: usize = 64 * 1024;11 pub const MAX_BATCH: usize = 64 * 1024;
15-/// A line longer than this is sent in pieces, so one line cannot grow without bound.
16 const MAX_LINE: usize = 16 * 1024;12 const MAX_LINE: usize = 16 * 1024;
17-/// How many resyncs one batch may take before the pump gives up.
18 const MAX_RESYNCS: u32 = 3;13 const MAX_RESYNCS: u32 = 3;
19 14
20-/// Errors from shipping logs.
21 #[derive(Debug, thiserror::Error)]15 #[derive(Debug, thiserror::Error)]
22 pub enum LogError {16 pub enum LogError {
23 #[error(transparent)]17 #[error(transparent)]
@@ -26,7 +20,6 @@ pub enum LogError {
26 Resync,20 Resync,
27 }21 }
28 22
29-/// Timing and retry settings for the pump.
30 #[derive(Clone, Copy, Debug)]23 #[derive(Clone, Copy, Debug)]
31 pub struct PumpConfig {24 pub struct PumpConfig {
32 pub flush_every: Duration,25 pub flush_every: Duration,
@@ -44,22 +37,9 @@ impl Default for PumpConfig {
44 }37 }
45 }38 }
46 39
47-/// Bytes kept for resends. Acknowledged bytes are trimmed past this, oldest first. Unacknowledged
48-/// bytes are never trimmed (they are at most one batch).
49 pub const RETAIN_CAP: usize = 2 * 1024 * 1024;40 pub const RETAIN_CAP: usize = 2 * 1024 * 1024;
50-/// Written in place of bytes the forge lost and the runner no longer holds.
51 pub const GAP_MARKER: &[u8] = b"[log gap]\n";41 pub const GAP_MARKER: &[u8] = b"[log gap]\n";
52 42
53-/// The job's log as the runner holds it, in forge coordinates (byte positions in the log the
54-/// forge stores).
55-///
56-/// - `offset` is the forge's confirmed size. Bytes below it were acknowledged with a 200.
57-/// - `start..end` is the retained window. It holds every byte from `start` up to `end`: the
58-/// acknowledged tail kept for resends, and the unacknowledged batch after `offset`.
59-/// - A 409 that reports size `S` inside the window resends from `S`. A size outside it leaves a
60-/// gap, which is marked with `GAP_MARKER`.
61-///
62-/// Pure state, so it can be tested without a network.
63 #[derive(Debug)]43 #[derive(Debug)]
64 pub struct LogBuffer {44 pub struct LogBuffer {
65 start: u64,45 start: u64,
@@ -79,7 +59,6 @@ impl LogBuffer {
79 Self::with_cap(RETAIN_CAP)59 Self::with_cap(RETAIN_CAP)
80 }60 }
81 61
82- /// A buffer that keeps at most `cap` bytes of acknowledged output. `cap` is at least one batch.
83 pub fn with_cap(cap: usize) -> Self {62 pub fn with_cap(cap: usize) -> Self {
84 Self {63 Self {
85 start: 0,64 start: 0,
@@ -89,47 +68,38 @@ impl LogBuffer {
89 }68 }
90 }69 }
91 70
92- /// The forge's confirmed size.
93 pub fn offset(&self) -> u64 {71 pub fn offset(&self) -> u64 {
94 self.offset72 self.offset
95 }73 }
96 74
97- /// The forge position of the oldest retained byte.
98 pub fn retained_start(&self) -> u64 {75 pub fn retained_start(&self) -> u64 {
99 self.start76 self.start
100 }77 }
101 78
102- /// The position just past the last byte the runner holds.
103 pub fn end(&self) -> u64 {79 pub fn end(&self) -> u64 {
104 self.start + self.data.len() as u6480 self.start + self.data.len() as u64
105 }81 }
106 82
107- /// Bytes the forge has not acknowledged.
108 pub fn pending(&self) -> usize {83 pub fn pending(&self) -> usize {
109 (self.end() - self.offset) as usize84 (self.end() - self.offset) as usize
110 }85 }
111 86
112- /// The next batch to send: up to `MAX_BATCH` unacknowledged bytes from `offset`.
113 pub fn batch(&self) -> Vec<u8> {87 pub fn batch(&self) -> Vec<u8> {
114 let from = (self.offset - self.start) as usize;88 let from = (self.offset - self.start) as usize;
115 let n = self.pending().min(MAX_BATCH);89 let n = self.pending().min(MAX_BATCH);
116 self.data.range(from..from + n).copied().collect()90 self.data.range(from..from + n).copied().collect()
117 }91 }
118 92
119- /// Room left before the pending bytes reach one batch.
120 pub fn room(&self) -> usize {93 pub fn room(&self) -> usize {
121 MAX_BATCH.saturating_sub(self.pending())94 MAX_BATCH.saturating_sub(self.pending())
122 }95 }
123 96
124- /// Appends as much of `bytes` as fits, and returns how many bytes were taken.
125 pub fn take(&mut self, bytes: &[u8]) -> usize {97 pub fn take(&mut self, bytes: &[u8]) -> usize {
126 let n = self.room().min(bytes.len());98 let n = self.room().min(bytes.len());
127 self.data.extend(&bytes[..n]);99 self.data.extend(&bytes[..n]);
128 n100 n
129 }101 }
130 102
131- /// The batch returned by `batch` was stored. Advances `offset` and trims the acknowledged
132- /// tail to the cap.
133 pub fn acked(&mut self) {103 pub fn acked(&mut self) {
134 self.offset += self.pending().min(MAX_BATCH) as u64;104 self.offset += self.pending().min(MAX_BATCH) as u64;
135 self.trim();105 self.trim();
@@ -149,11 +119,6 @@ impl LogBuffer {
149 }119 }
150 }120 }
151 121
152- /// The forge reports that it holds `held` bytes. Returns true when nothing is pending.
153- ///
154- /// - If `held` is inside the retained window, the runner resends from `held`.
155- /// - Otherwise the bytes between `held` and the window are unavailable. The runner writes
156- /// `GAP_MARKER` at `held`, then continues with what it still holds.
157 pub fn resync(&mut self, held: u64) -> bool {122 pub fn resync(&mut self, held: u64) -> bool {
158 if held >= self.start && held <= self.end() {123 if held >= self.start && held <= self.end() {
159 self.offset = held;124 self.offset = held;
@@ -165,7 +130,6 @@ impl LogBuffer {
165 "forge log size is outside the retained window, marking a log gap"130 "forge log size is outside the retained window, marking a log gap"
166 );131 );
167 let kept: VecDeque<u8> = if held < self.start {132 let kept: VecDeque<u8> = if held < self.start {
168- // Keep the retained bytes after the marker.
169 GAP_MARKER133 GAP_MARKER
170 .iter()134 .iter()
171 .copied()135 .copied()
@@ -182,10 +146,6 @@ impl LogBuffer {
182 }146 }
183 }147 }
184 148
185-/// Ships `rx` to the forge: mask each chunk, batch it, and POST it with its offset.
186-///
187-/// Returns the number of bytes the forge holds for this job once `rx` is closed and the last
188-/// batch is stored.
189 pub async fn pump(149 pub async fn pump(
190 client: &ForgeClient,150 client: &ForgeClient,
191 job_id: &str,151 job_id: &str,
@@ -237,7 +197,6 @@ async fn append(
237 Ok(())197 Ok(())
238 }198 }
239 199
240-/// Sends the pending batch until the forge has it, retrying transient errors.
241 async fn send(200 async fn send(
242 buf: &mut LogBuffer,201 buf: &mut LogBuffer,
243 client: &ForgeClient,202 client: &ForgeClient,
@@ -279,9 +238,6 @@ async fn send(
279 Ok(())238 Ok(())
280 }239 }
281 240
282-/// Reads `reader` and sends its output to `tx`, one line per message. A line longer than
283-/// `MAX_LINE` is split. If the receiver goes away, the reader keeps draining so the child does
284-/// not block on a full pipe.
285 pub async fn forward_lines<R>(reader: R, tx: mpsc::Sender<Vec<u8>>)241 pub async fn forward_lines<R>(reader: R, tx: mpsc::Sender<Vec<u8>>)
286 where242 where
287 R: AsyncRead + Unpin,243 R: AsyncRead + Unpin,
@@ -306,7 +262,6 @@ where
306 };262 };
307 reader.consume(take);263 reader.consume(take);
308 if done || line.len() >= MAX_LINE {264 if done || line.len() >= MAX_LINE {
309- // Once the receiver is gone, drop the line instead of letting it grow.
310 if alive {265 if alive {
311 alive = tx.send(std::mem::take(&mut line)).await.is_ok();266 alive = tx.send(std::mem::take(&mut line)).await.is_ok();
312 } else {267 } else {
@@ -338,14 +293,10 @@ mod tests {
338 293
339 #[test]294 #[test]
340 fn resync_to_the_forge_offset() {295 fn resync_to_the_forge_offset() {
341- // (bytes sent, size the forge reports, resync result, offset after, batch after)
342 type Case = (&'static [u8], u64, bool, u64, &'static [u8]);296 type Case = (&'static [u8], u64, bool, u64, &'static [u8]);
343 let cases: &[Case] = &[297 let cases: &[Case] = &[
344- // The response to "abcdef" was lost and the forge stored it, so nothing is resent.
345 (b"abcdef", 6, true, 6, b""),298 (b"abcdef", 6, true, 6, b""),
346- // The forge holds 2 bytes, so the uncovered tail is resent.
347 (b"abcdef", 2, false, 2, b"cdef"),299 (b"abcdef", 2, false, 2, b"cdef"),
348- // The forge is ahead of everything we hold, which marks a gap.
349 (b"ab", 10, false, 10, GAP_MARKER),300 (b"ab", 10, false, 10, GAP_MARKER),
350 ];301 ];
351 for (sent, held, want_ok, want_offset, want_batch) in cases {302 for (sent, held, want_ok, want_offset, want_batch) in cases {
@@ -359,7 +310,6 @@ mod tests {
359 310
360 #[test]311 #[test]
361 fn resync_inside_the_window_resends_acknowledged_bytes() {312 fn resync_inside_the_window_resends_acknowledged_bytes() {
362- // "abc" was acknowledged, "def" is pending. The forge then reports size 1.
363 let mut buf = LogBuffer::new();313 let mut buf = LogBuffer::new();
364 buf.take(b"abc");314 buf.take(b"abc");
365 buf.acked();315 buf.acked();
@@ -372,14 +322,12 @@ mod tests {
372 322
373 #[test]323 #[test]
374 fn resync_below_the_window_marks_a_gap_and_keeps_the_rest() {324 fn resync_below_the_window_marks_a_gap_and_keeps_the_rest() {
375- // Two full batches are acknowledged. A one-batch cap trims the first.
376 let mut small = LogBuffer::with_cap(MAX_BATCH);325 let mut small = LogBuffer::with_cap(MAX_BATCH);
377 small.take(&vec![b'a'; MAX_BATCH]);326 small.take(&vec![b'a'; MAX_BATCH]);
378 small.acked();327 small.acked();
379 small.take(&vec![b'b'; MAX_BATCH]);328 small.take(&vec![b'b'; MAX_BATCH]);
380 small.acked();329 small.acked();
381 assert_eq!(small.retained_start(), MAX_BATCH as u64);330 assert_eq!(small.retained_start(), MAX_BATCH as u64);
382- // The forge says it holds 1 byte, which is below the window. The bytes 1..start are gone.
383 assert!(!small.resync(1));331 assert!(!small.resync(1));
384 assert_eq!(small.offset(), 1);332 assert_eq!(small.offset(), 1);
385 let batch = small.batch();333 let batch = small.batch();
@@ -394,7 +342,6 @@ mod tests {
394 buf.take(&vec![b'a'; MAX_BATCH]);342 buf.take(&vec![b'a'; MAX_BATCH]);
395 buf.acked();343 buf.acked();
396 buf.take(b"tail");344 buf.take(b"tail");
397- // The cap is one batch, so the acked batch is trimmed once it is acked.
398 buf.acked();345 buf.acked();
399 assert_eq!(buf.offset(), (MAX_BATCH + 4) as u64);346 assert_eq!(buf.offset(), (MAX_BATCH + 4) as u64);
400 assert!(buf.retained_start() > 0);347 assert!(buf.retained_start() > 0);
crates/forge-runner/src/main.rsmodified+0 -5
@@ -1,7 +1,3 @@
1-//! `forge-runner`: `register` once per machine, then `run` to claim and execute jobs.
2-//!
3-//! The same command line is available as `forge runner`. See `forge_runner::cli`.
4-
5 use std::process::ExitCode;1 use std::process::ExitCode;
6 2
7 fn main() -> ExitCode {3 fn main() -> ExitCode {
@@ -10,7 +6,6 @@ fn main() -> ExitCode {
10 env!("FORGE_GIT_DATE"),6 env!("FORGE_GIT_DATE"),
11 matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"),7 matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"),
12 );8 );
13- // The hidden helpers run before any runtime or subscriber exists.
14 if forge_runner::cli::is_sandbox_invocation() {9 if forge_runner::cli::is_sandbox_invocation() {
15 std::process::exit(forge_runner::cli::hidden_main());10 std::process::exit(forge_runner::cli::hidden_main());
16 }11 }
crates/forge-runner/src/memory.rsmodified+0 -41
@@ -1,31 +1,16 @@
1-//! Memory-aware admission. The runner has a memory budget for jobs and every running job holds a
2-//! reservation against it. A claim tells the forge how much is free, so the forge hands out only a
3-//! job that fits. The concurrency limit stays as a second cap, see [`crate::limiter`].
4-//!
5-//! Reservations are promises, not measurements: nothing reads what a job really uses. Each job's
6-//! cgroup limit (see `Limits::for_job`) is what makes the promise hold, so a job that exceeds
7-//! its reservation is OOM-killed inside its own cgroup and not by the host.
8-
9 use std::sync::{Arc, Mutex, PoisonError};1 use std::sync::{Arc, Mutex, PoisonError};
10 2
11 use forge_ci::size::{format_size, parse_size};3 use forge_ci::size::{format_size, parse_size};
12 4
13 use crate::config::Limits;5 use crate::config::Limits;
14 6
15-/// Used when a configured size does not parse. `Limits::default` carries the same value.
16 const FALLBACK_RESERVE: u64 = 1 << 30;7 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.
18 const MIN_BUDGET: u64 = 256 << 20;8 const MIN_BUDGET: u64 = 256 << 20;
19 9
20-/// What a job reserves: its declared memory or the default, never more than the budget. A job
21-/// bigger than the whole budget therefore still runs, alone, instead of waiting forever.
22 pub fn reservation(declared: Option<u64>, default_reserve: u64, budget: u64) -> u64 {10 pub fn reservation(declared: Option<u64>, default_reserve: u64, budget: u64) -> u64 {
23 declared.unwrap_or(default_reserve).min(budget).max(1)11 declared.unwrap_or(default_reserve).min(budget).max(1)
24 }12 }
25 13
26-/// The budget when none is configured: MemTotal minus the headroom, plus `swap_percent` of the
27-/// swap. The headroom is the larger of `headroom` and 10% of MemTotal. Never below half of
28-/// MemTotal or [`MIN_BUDGET`], so a small host still takes jobs.
29 pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent: u32) -> u64 {14 pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent: u32) -> u64 {
30 let keep = headroom.max(mem_total / 10);15 let keep = headroom.max(mem_total / 10);
31 let ram = mem_total.saturating_sub(keep).max(mem_total / 2);16 let ram = mem_total.saturating_sub(keep).max(mem_total / 2);
@@ -33,7 +18,6 @@ pub fn auto_budget(mem_total: u64, swap_total: u64, headroom: u64, swap_percent:
33 ram.saturating_add(swap).max(MIN_BUDGET)18 ram.saturating_add(swap).max(MIN_BUDGET)
34 }19 }
35 20
36-/// The fields of a `/proc/meminfo` text the runner reads, in bytes. A missing field is `None`.
37 #[derive(Default)]21 #[derive(Default)]
38 pub struct Meminfo {22 pub struct Meminfo {
39 pub total: Option<u64>,23 pub total: Option<u64>,
@@ -41,7 +25,6 @@ pub struct Meminfo {
41 pub swap_total: Option<u64>,25 pub swap_total: Option<u64>,
42 }26 }
43 27
44-/// Parses a `/proc/meminfo` text. The file reports kibibytes.
45 pub fn meminfo(text: &str) -> Meminfo {28 pub fn meminfo(text: &str) -> Meminfo {
46 let find = |key: &str| {29 let find = |key: &str| {
47 let line = text.lines().find(|l| l.starts_with(key))?;30 let line = text.lines().find(|l| l.starts_with(key))?;
@@ -61,12 +44,10 @@ fn host_memory() -> Meminfo {
61 .unwrap_or_default()44 .unwrap_or_default()
62 }45 }
63 46
64-/// A budget set in `runner.toml` or by the forge. `None` in `auto` mode.
65 fn fixed_budget(limits: &Limits) -> Option<u64> {47 fn fixed_budget(limits: &Limits) -> Option<u64> {
66 limits.memory_budget.as_deref().and_then(parse_size)48 limits.memory_budget.as_deref().and_then(parse_size)
67 }49 }
68 50
69-/// The budget `limits` asks for on a host with this much memory and swap.
70 fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 {51 fn configured_budget(limits: &Limits, mem_total: u64, swap_total: u64) -> u64 {
71 fixed_budget(limits).map_or_else(52 fixed_budget(limits).map_or_else(
72 || {53 || {
@@ -84,8 +65,6 @@ struct State {
84 reserved: u64,65 reserved: u64,
85 }66 }
86 67
87-/// The part of the budget that is swap: `swap_percent` of the swap in `auto` mode, none with a set
88-/// budget. A lone job may use it as swap on top of the rest of the budget, which is RAM.
89 fn swap_share(limits: &Limits, swap_total: u64) -> u64 {68 fn swap_share(limits: &Limits, swap_total: u64) -> u64 {
90 if fixed_budget(limits).is_some() {69 if fixed_budget(limits).is_some() {
91 return 0;70 return 0;
@@ -93,7 +72,6 @@ fn swap_share(limits: &Limits, swap_total: u64) -> u64 {
93 (u128::from(swap_total) * u128::from(limits.budget_swap_percent.min(100)) / 100) as u6472 (u128::from(swap_total) * u128::from(limits.budget_swap_percent.min(100)) / 100) as u64
94 }73 }
95 74
96-/// The runner's memory budget and the reservations against it. Cheap to share: clone the `Arc`.
97 pub struct MemoryGate {75 pub struct MemoryGate {
98 limits: Limits,76 limits: Limits,
99 mem_total: u64,77 mem_total: u64,
@@ -101,7 +79,6 @@ pub struct MemoryGate {
101 state: Mutex<State>,79 state: Mutex<State>,
102 }80 }
103 81
104-/// A job's reservation. Dropping it gives the memory back.
105 pub struct Reservation {82 pub struct Reservation {
106 bytes: u64,83 bytes: u64,
107 gate: Arc<MemoryGate>,84 gate: Arc<MemoryGate>,
@@ -115,8 +92,6 @@ impl Drop for Reservation {
115 }92 }
116 93
117 impl MemoryGate {94 impl MemoryGate {
118- /// A gate for this host, read from `/proc/meminfo`. Without it the host is assumed to have
119- /// 8 GiB.
120 pub fn for_host(limits: &Limits) -> Arc<Self> {95 pub fn for_host(limits: &Limits) -> Arc<Self> {
121 let host = host_memory();96 let host = host_memory();
122 Self::new(97 Self::new(
@@ -150,12 +125,10 @@ impl MemoryGate {
150 self.lock().budget125 self.lock().budget
151 }126 }
152 127
153- /// The swap part of the budget, see [`swap_share`].
154 pub fn swap(&self) -> u64 {128 pub fn swap(&self) -> u64 {
155 self.lock().swap129 self.lock().swap
156 }130 }
157 131
158- /// The RAM part of the budget: what the box and a lone job may hold in memory.
159 pub fn ram_budget(&self) -> u64 {132 pub fn ram_budget(&self) -> u64 {
160 let state = self.lock();133 let state = self.lock();
161 state.budget.saturating_sub(state.swap).max(MIN_BUDGET)134 state.budget.saturating_sub(state.swap).max(MIN_BUDGET)
@@ -165,15 +138,11 @@ impl MemoryGate {
165 self.lock().reserve138 self.lock().reserve
166 }139 }
167 140
168- /// What a new claim may admit: the budget minus the running jobs' reservations.
169 pub fn free(&self) -> u64 {141 pub fn free(&self) -> u64 {
170 let state = self.lock();142 let state = self.lock();
171 state.budget.saturating_sub(state.reserved)143 state.budget.saturating_sub(state.reserved)
172 }144 }
173 145
174- /// Reserves memory for a claimed job. This always succeeds: the forge has already checked the
175- /// job fits, and a job that was handed out must run. An older forge that does not check can
176- /// leave the runner over its budget, and `free` then reads 0 until jobs finish.
177 pub fn reserve(self: &Arc<Self>, declared: Option<u64>) -> Reservation {146 pub fn reserve(self: &Arc<Self>, declared: Option<u64>) -> Reservation {
178 let mut state = self.lock();147 let mut state = self.lock();
179 let bytes = reservation(declared, state.reserve, state.budget);148 let bytes = reservation(declared, state.reserve, state.budget);
@@ -184,9 +153,6 @@ impl MemoryGate {
184 }153 }
185 }154 }
186 155
187- /// Applies what the forge asked for, the way `Limiter::apply` does for concurrency: `Some`
188- /// is an override, `None` brings back the `runner.toml` value. A value that does not parse
189- /// counts as no override. Returns a log line when something changed.
190 pub fn apply(&self, budget: Option<&str>, reserve: Option<&str>) -> Option<String> {156 pub fn apply(&self, budget: Option<&str>, reserve: Option<&str>) -> Option<String> {
191 let mut limits = self.limits.clone();157 let mut limits = self.limits.clone();
192 if let Some(text) = budget.filter(|t| *t == "auto" || parse_size(t).is_some()) {158 if let Some(text) = budget.filter(|t| *t == "auto" || parse_size(t).is_some()) {
@@ -215,7 +181,6 @@ impl MemoryGate {
215 Some(line)181 Some(line)
216 }182 }
217 183
218- /// Like [`MemoryGate::apply`], and logs the change.
219 pub fn apply_logged(&self, budget: Option<&str>, reserve: Option<&str>) {184 pub fn apply_logged(&self, budget: Option<&str>, reserve: Option<&str>) {
220 if let Some(line) = self.apply(budget, reserve) {185 if let Some(line) = self.apply(budget, reserve) {
221 tracing::info!("{line}");186 tracing::info!("{line}");
@@ -254,16 +219,12 @@ mod tests {
254 219
255 #[test]220 #[test]
256 fn auto_budget_is_mem_total_minus_headroom() {221 fn auto_budget_is_mem_total_minus_headroom() {
257- // The production host: 7.6 GiB RAM, 8 GiB swap, 1 GiB headroom, swap ignored.
258 let total = 7 * GIB + 6 * GIB / 10;222 let total = 7 * GIB + 6 * GIB / 10;
259 let budget = auto_budget(total, 8 * GIB, GIB, 0);223 let budget = auto_budget(total, 8 * GIB, GIB, 0);
260 assert_eq!(budget, total - GIB);224 assert_eq!(budget, total - GIB);
261 assert!(budget > 6 * GIB && budget < 7 * GIB);225 assert!(budget > 6 * GIB && budget < 7 * GIB);
262- // On a big host 10% wins over 1 GiB.
263 assert_eq!(auto_budget(64 * GIB, 0, GIB, 0), 64 * GIB - 64 * GIB / 10);226 assert_eq!(auto_budget(64 * GIB, 0, GIB, 0), 64 * GIB - 64 * GIB / 10);
264- // Half of the swap counted.
265 assert_eq!(auto_budget(total, 8 * GIB, GIB, 50), total - GIB + 4 * GIB);227 assert_eq!(auto_budget(total, 8 * GIB, GIB, 50), total - GIB + 4 * GIB);
266- // A tiny host keeps at least half.
267 assert_eq!(auto_budget(GIB, 0, 2 * GIB, 0), GIB / 2);228 assert_eq!(auto_budget(GIB, 0, 2 * GIB, 0), GIB / 2);
268 }229 }
269 230
@@ -321,11 +282,9 @@ mod tests {
321 assert_eq!(gate.budget(), 5 * GIB);282 assert_eq!(gate.budget(), 5 * GIB);
322 assert_eq!(gate.default_reserve(), 2 * GIB);283 assert_eq!(gate.default_reserve(), 2 * GIB);
323 assert_eq!(gate.apply(Some("5g"), Some("2g")), None, "no change");284 assert_eq!(gate.apply(Some("5g"), Some("2g")), None, "no change");
324- // No override brings the runner.toml values back.
325 gate.apply(None, None);285 gate.apply(None, None);
326 assert_eq!(gate.default_reserve(), GIB);286 assert_eq!(gate.default_reserve(), GIB);
327 assert_ne!(gate.budget(), 5 * GIB);287 assert_ne!(gate.budget(), 5 * GIB);
328- // Nonsense is ignored.
329 gate.apply(Some("lots"), Some("0"));288 gate.apply(Some("lots"), Some("0"));
330 assert_eq!(gate.default_reserve(), GIB);289 assert_eq!(gate.default_reserve(), GIB);
331 }290 }
crates/forge-runner/src/metrics.rsmodified+0 -23
@@ -1,8 +1,3 @@
1-//! Host metrics for the graphs on the runner's admin page. Every [`EVERY`] the runner reads
2-//! `/proc` (CPU, memory, network) and turns the counters into a sample: CPU share and rates since
3-//! the previous reading. [`ship`] posts the buffered samples every [`FLUSH_EVERY`] ticks. On a
4-//! host without a readable `/proc` nothing is sampled and nothing is sent.
5-
6 use std::collections::VecDeque;1 use std::collections::VecDeque;
7 use std::path::Path;2 use std::path::Path;
8 use std::time::{Duration, Instant};3 use std::time::{Duration, Instant};
@@ -14,15 +9,10 @@ use tokio_util::sync::CancellationToken;
14 use crate::client::{ClientError, ForgeClient};9 use crate::client::{ClientError, ForgeClient};
15 use crate::selflog::now_ms;10 use crate::selflog::now_ms;
16 11
17-/// Time between two samples.
18 pub const EVERY: Duration = Duration::from_secs(5);12 pub const EVERY: Duration = Duration::from_secs(5);
19-/// The buffer is posted on every this many ticks.
20 const FLUSH_EVERY: u64 = 2;13 const FLUSH_EVERY: u64 = 2;
21-/// Most samples the buffer holds while the forge cannot be reached (an hour). The oldest go first.
22 pub const CAPACITY: usize = 360;14 pub const CAPACITY: usize = 360;
23 15
24-/// Counters read from `/proc` at one moment. Busy and total are CPU jiffies, the others are
25-/// memory in bytes and network bytes since boot.
26 #[derive(Clone, Copy, Debug, PartialEq, Eq)]16 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
27 pub struct Snapshot {17 pub struct Snapshot {
28 pub busy: u64,18 pub busy: u64,
@@ -35,7 +25,6 @@ pub struct Snapshot {
35 pub disk_total: u64,25 pub disk_total: u64,
36 }26 }
37 27
38-/// `(busy, total)` jiffies of the first `cpu ` line of `/proc/stat`. Idle includes iowait.
39 pub fn parse_cpu(text: &str) -> Option<(u64, u64)> {28 pub fn parse_cpu(text: &str) -> Option<(u64, u64)> {
40 let line = text29 let line = text
41 .lines()30 .lines()
@@ -55,8 +44,6 @@ pub fn parse_cpu(text: &str) -> Option<(u64, u64)> {
55 Some((total.saturating_sub(idle), total))44 Some((total.saturating_sub(idle), total))
56 }45 }
57 46
58-/// `(rx, tx)` bytes summed over the interfaces of `/proc/net/dev` except `lo`. The two header
59-/// lines have no colon and are skipped.
60 pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> {47 pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> {
61 let (mut rx, mut tx, mut seen) = (0_u64, 0_u64, false);48 let (mut rx, mut tx, mut seen) = (0_u64, 0_u64, false);
62 for line in text.lines() {49 for line in text.lines() {
@@ -83,7 +70,6 @@ pub fn parse_net_dev(text: &str) -> Option<(u64, u64)> {
83 seen.then_some((rx, tx))70 seen.then_some((rx, tx))
84 }71 }
85 72
86-/// Reads the three `/proc` files. `None` when any of them is missing or unreadable.
87 pub fn read_snapshot(work_dir: &Path) -> Option<Snapshot> {73 pub fn read_snapshot(work_dir: &Path) -> Option<Snapshot> {
88 let stat = std::fs::read_to_string("/proc/stat").ok()?;74 let stat = std::fs::read_to_string("/proc/stat").ok()?;
89 let mem = std::fs::read_to_string("/proc/meminfo").ok()?;75 let mem = std::fs::read_to_string("/proc/meminfo").ok()?;
@@ -105,7 +91,6 @@ pub fn read_snapshot(work_dir: &Path) -> Option<Snapshot> {
105 })91 })
106 }92 }
107 93
108-/// Used and total bytes of the filesystem holding `path`.
109 pub fn disk_usage(path: &Path) -> Option<(u64, u64)> {94 pub fn disk_usage(path: &Path) -> Option<(u64, u64)> {
110 let stat = nix::sys::statvfs::statvfs(path).ok()?;95 let stat = nix::sys::statvfs::statvfs(path).ok()?;
111 let unit = stat.fragment_size();96 let unit = stat.fragment_size();
@@ -114,14 +99,12 @@ pub fn disk_usage(path: &Path) -> Option<(u64, u64)> {
114 Some((total.saturating_sub(free), total))99 Some((total.saturating_sub(free), total))
115 }100 }
116 101
117-/// Turns successive snapshots into samples. The first snapshot only sets the baseline.
118 #[derive(Default)]102 #[derive(Default)]
119 pub struct Sampler {103 pub struct Sampler {
120 prev: Option<(Instant, Snapshot)>,104 prev: Option<(Instant, Snapshot)>,
121 }105 }
122 106
123 impl Sampler {107 impl Sampler {
124- /// The sample for `snap`, taken at `now`, or `None` for the first reading.
125 pub fn feed(108 pub fn feed(
126 &mut self,109 &mut self,
127 now: Instant,110 now: Instant,
@@ -141,7 +124,6 @@ impl Sampler {
141 } else {124 } else {
142 (db as f64 / dt as f64 * 100.0).clamp(0.0, 100.0)125 (db as f64 / dt as f64 * 100.0).clamp(0.0, 100.0)
143 };126 };
144- // Saturating `as` casts keep a negative or huge rate in range.
145 let rate =127 let rate =
146 |now_v: u64, before_v: u64| (now_v.saturating_sub(before_v) as f64 / secs) as u64;128 |now_v: u64, before_v: u64| (now_v.saturating_sub(before_v) as f64 / secs) as u64;
147 Some(RunnerSample {129 Some(RunnerSample {
@@ -158,10 +140,6 @@ impl Sampler {
158 }140 }
159 }141 }
160 142
161-/// Samples the host every [`EVERY`] and posts the buffer every [`FLUSH_EVERY`] ticks. `running`
162-/// gives the jobs on the runner now. A failed post keeps the buffer for the next one. An older
163-/// forge without the endpoint answers 404, and then sampling stops for good. When `stop` is
164-/// cancelled, the buffer gets one last post before returning.
165 pub async fn ship(143 pub async fn ship(
166 client: ForgeClient,144 client: ForgeClient,
167 runner_secret: String,145 runner_secret: String,
@@ -217,7 +195,6 @@ mod tests {
217 #[test]195 #[test]
218 fn cpu_busy_excludes_idle_and_iowait() {196 fn cpu_busy_excludes_idle_and_iowait() {
219 let text = "cpu 100 10 50 800 40 5 5 0 0 0\ncpu0 50 5 25 400 20 2 2 0 0 0\n";197 let text = "cpu 100 10 50 800 40 5 5 0 0 0\ncpu0 50 5 25 400 20 2 2 0 0 0\n";
220- // Total 1010, idle 840, so busy 170.
221 assert_eq!(parse_cpu(text), Some((170, 1010)));198 assert_eq!(parse_cpu(text), Some((170, 1010)));
222 }199 }
223 200
crates/forge-runner/src/oci/helper.rsmodified+0 -12
@@ -1,7 +1,3 @@
1-//! The subuid unpack helper. [`unpack_helper_main`] is the body of `forge-runner __sandbox-unpack`.
2-//! It runs inside the mapped user namespace, so files it writes get the subordinate owners from the
3-//! layers. [`run_unpack_helper`] is the runner side that starts it.
4-
5 use std::io::{self, Read, Write};1 use std::io::{self, Read, Write};
6 use std::path::{Path, PathBuf};2 use std::path::{Path, PathBuf};
7 use std::process::{Command, Stdio};3 use std::process::{Command, Stdio};
@@ -11,7 +7,6 @@ use serde::{Deserialize, Serialize};
11 use super::unpack::{Ownership, UnpackError, UnpackStats, unpack_layers};7 use super::unpack::{Ownership, UnpackError, UnpackStats, unpack_layers};
12 use crate::sandbox::idmap::{IdMap, enter_mapped_userns};8 use crate::sandbox::idmap::{IdMap, enter_mapped_userns};
13 9
14-/// What the runner writes to the helper's stdin, as JSON.
15 #[derive(Debug, Clone, Serialize, Deserialize)]10 #[derive(Debug, Clone, Serialize, Deserialize)]
16 pub(super) struct UnpackRequest {11 pub(super) struct UnpackRequest {
17 pub map: IdMap,12 pub map: IdMap,
@@ -20,7 +15,6 @@ pub(super) struct UnpackRequest {
20 pub max_bytes: u64,15 pub max_bytes: u64,
21 }16 }
22 17
23-/// Runs `<exe> __sandbox-unpack` with `req` on stdin and returns the stats it prints on stdout.
24 pub(super) fn run_unpack_helper(18 pub(super) fn run_unpack_helper(
25 exe: &Path,19 exe: &Path,
26 req: &UnpackRequest,20 req: &UnpackRequest,
@@ -33,8 +27,6 @@ pub(super) fn run_unpack_helper(
33 .stderr(Stdio::piped())27 .stderr(Stdio::piped())
34 .spawn()?;28 .spawn()?;
35 if let Some(mut stdin) = child.stdin.take() {29 if let Some(mut stdin) = child.stdin.take() {
36- // A helper that exits early says why on stderr, which is reported below, so a failed
37- // write is not an error of its own here.
38 let _ = stdin.write_all(&body);30 let _ = stdin.write_all(&body);
39 }31 }
40 let out = child.wait_with_output()?;32 let out = child.wait_with_output()?;
@@ -50,10 +42,6 @@ pub(super) fn run_unpack_helper(
50 .map_err(|err| UnpackError::Helper(format!("bad stats from the helper: {err}")))42 .map_err(|err| UnpackError::Helper(format!("bad stats from the helper: {err}")))
51 }43 }
52 44
53-/// Entry point for `forge-runner __sandbox-unpack`. Returns the process exit code: 0 after the
54-/// stats are printed, or 125 with a `forge-sandbox:` line on stderr.
55-///
56-/// Must run before any thread is started, because it enters a user namespace.
57 pub fn unpack_helper_main() -> i32 {45 pub fn unpack_helper_main() -> i32 {
58 match run_helper() {46 match run_helper() {
59 Ok(()) => 0,47 Ok(()) => 0,
crates/forge-runner/src/oci/mod.rsmodified+0 -15
@@ -1,13 +1,3 @@
1-//! The builtin image store: pulls OCI images, unpacks them into rootfs directories and garbage
2-//! collects them. Everything lives under one root directory:
3-//!
4-//! - `blobs/sha256/<hex>`: verified layer blobs, as pulled (compressed)
5-//! - `rootfs/<hex>/`: the unpacked rootfs for one manifest digest
6-//! - `meta/<hex>.json`: env, working dir, user and layer digests for that rootfs
7-//! - `tags/<encoded ref>`: the digest that a reference last resolved to
8-//! - `locks/<hex>.lock`: held while an image is pulled or unpacked
9-//! - `last_used/<hex>`: a stamp file, touched on every use, for garbage collection
10-
11 mod helper;1 mod helper;
12 mod pull;2 mod pull;
13 mod store;3 mod store;
@@ -20,7 +10,6 @@ pub use helper::unpack_helper_main;
20 pub use store::{GcStats, ImageStore};10 pub use store::{GcStats, ImageStore};
21 pub use unpack::{Ownership, UnpackError, UnpackStats};11 pub use unpack::{Ownership, UnpackError, UnpackStats};
22 12
23-/// Errors from pulling, verifying, unpacking or collecting images.
24 #[derive(Debug, thiserror::Error)]13 #[derive(Debug, thiserror::Error)]
25 pub enum ImageError {14 pub enum ImageError {
26 #[error("invalid image reference {image}: {reason}")]15 #[error("invalid image reference {image}: {reason}")]
@@ -47,7 +36,6 @@ pub enum ImageError {
47 Task(#[from] tokio::task::JoinError),36 Task(#[from] tokio::task::JoinError),
48 }37 }
49 38
50-/// Basic-auth credentials for a registry. The password is never printed.
51 #[derive(Clone)]39 #[derive(Clone)]
52 pub struct RegistryAuth {40 pub struct RegistryAuth {
53 pub username: String,41 pub username: String,
@@ -63,13 +51,10 @@ impl fmt::Debug for RegistryAuth {
63 }51 }
64 }52 }
65 53
66-/// An image ready to run: its rootfs directory and the settings from its config.
67 #[derive(Debug, Clone, PartialEq, Eq)]54 #[derive(Debug, Clone, PartialEq, Eq)]
68 pub struct PreparedImage {55 pub struct PreparedImage {
69 pub rootfs: PathBuf,56 pub rootfs: PathBuf,
70- /// The manifest digest, `sha256:<hex>`.
71 pub digest: String,57 pub digest: String,
72- /// The image config `Env` list, as `NAME=value` strings. Empty when the image sets none.
73 pub env: Vec<String>,58 pub env: Vec<String>,
74 pub working_dir: Option<String>,59 pub working_dir: Option<String>,
75 pub user: Option<String>,60 pub user: Option<String>,
crates/forge-runner/src/oci/pull.rsmodified+0 -23
@@ -1,5 +1,3 @@
1-//! Resolving an image reference, pulling its manifest and layers, and unpacking them.
2-
3 use std::fs::{self, Permissions};1 use std::fs::{self, Permissions};
4 use std::os::unix::fs::PermissionsExt;2 use std::os::unix::fs::PermissionsExt;
5 use std::path::PathBuf;3 use std::path::PathBuf;
@@ -18,16 +16,9 @@ use super::store::{ImageMeta, ImageStore, lock_file};
18 use super::unpack::{Ownership, UnpackStats, unpack_layers};16 use super::unpack::{Ownership, UnpackStats, unpack_layers};
19 use super::{ImageError, PreparedImage, RegistryAuth};17 use super::{ImageError, PreparedImage, RegistryAuth};
20 18
21-/// Largest image config blob the runner will read into memory.
22 const MAX_CONFIG_BYTES: i64 = 4 * 1024 * 1024;19 const MAX_CONFIG_BYTES: i64 = 4 * 1024 * 1024;
23 20
24 impl ImageStore {21 impl ImageStore {
25- /// Makes `image` available as an unpacked rootfs and returns it with its config.
26- ///
27- /// The manifest is always fetched, so the digest is current. When the digest already has an
28- /// unpacked rootfs, nothing else is downloaded. Missing layer blobs are downloaded and checked
29- /// against their digest. When the registry cannot be reached and the tag was pulled before,
30- /// the cached image is used and a warning is logged. Progress lines go to `log`.
31 pub async fn ensure(22 pub async fn ensure(
32 &self,23 &self,
33 image: &str,24 image: &str,
@@ -120,7 +111,6 @@ impl ImageStore {
120 {111 {
121 Ok(stats) => stats,112 Ok(stats) => stats,
122 Err(err) => {113 Err(err) => {
123- // Subordinate-owned files stay behind if the runner removes them directly.
124 let _ = self.remove_entry(&staging_path);114 let _ = self.remove_entry(&staging_path);
125 return Err(err);115 return Err(err);
126 }116 }
@@ -143,7 +133,6 @@ impl ImageStore {
143 .await;133 .await;
144 }134 }
145 135
146- // The rootfs must be readable by the container user, whatever the tempdir default is.
147 fs::set_permissions(staging.path(), Permissions::from_mode(0o755))?;136 fs::set_permissions(staging.path(), Permissions::from_mode(0o755))?;
148 let unpacked = staging.keep();137 let unpacked = staging.keep();
149 let final_dir = self.rootfs_path(&hex);138 let final_dir = self.rootfs_path(&hex);
@@ -168,8 +157,6 @@ impl ImageStore {
168 Ok(self.prepared(&hex, meta))157 Ok(self.prepared(&hex, meta))
169 }158 }
170 159
171- /// Unpacks `layers` into the staging dir `staging`. A subuid map unpacks in the helper process,
172- /// so the files get subordinate owners. A single map unpacks in this process as before.
173 async fn unpack_into(160 async fn unpack_into(
174 &self,161 &self,
175 staging: PathBuf,162 staging: PathBuf,
@@ -195,7 +182,6 @@ impl ImageStore {
195 Ok(stats)182 Ok(stats)
196 }183 }
197 184
198- /// Downloads one layer blob into a temp file, checks its digest, and renames it into place.
199 async fn download_blob(185 async fn download_blob(
200 &self,186 &self,
201 client: &Client,187 client: &Client,
@@ -229,7 +215,6 @@ impl ImageStore {
229 }215 }
230 }216 }
231 217
232-/// The parts of an image config that the runner uses.
233 #[derive(Deserialize)]218 #[derive(Deserialize)]
234 struct ConfigFile {219 struct ConfigFile {
235 #[serde(default)]220 #[serde(default)]
@@ -246,8 +231,6 @@ struct ContainerConfig {
246 user: Option<String>,231 user: Option<String>,
247 }232 }
248 233
249-/// Parses an image reference, applying the Docker Hub defaults: `alpine` is
250-/// `docker.io/library/alpine:latest`.
251 pub(super) fn parse_reference(image: &str) -> Result<Reference, ImageError> {234 pub(super) fn parse_reference(image: &str) -> Result<Reference, ImageError> {
252 image235 image
253 .parse::<Reference>()236 .parse::<Reference>()
@@ -257,8 +240,6 @@ pub(super) fn parse_reference(image: &str) -> Result<Reference, ImageError> {
257 })240 })
258 }241 }
259 242
260-/// Returns the hex part of a `sha256:<hex>` digest. The digest comes from a registry and becomes
261-/// a file name, so anything other than 64 lowercase hex digits is refused.
262 pub(super) fn hex_of(digest: &str) -> Result<&str, ImageError> {243 pub(super) fn hex_of(digest: &str) -> Result<&str, ImageError> {
263 let hex = digest244 let hex = digest
264 .strip_prefix("sha256:")245 .strip_prefix("sha256:")
@@ -291,7 +272,6 @@ async fn sha256_file(path: PathBuf) -> Result<String, ImageError> {
291 Ok(tokio::task::spawn_blocking(move || crate::update::file_sha256(&path)).await??)272 Ok(tokio::task::spawn_blocking(move || crate::update::file_sha256(&path)).await??)
292 }273 }
293 274
294-/// Sends one line to the job log. A closed log channel is not an error for the pull.
295 async fn log_line(log: &mpsc::Sender<Vec<u8>>, line: String) {275 async fn log_line(log: &mpsc::Sender<Vec<u8>>, line: String) {
296 let mut bytes = line.into_bytes();276 let mut bytes = line.into_bytes();
297 bytes.push(b'\n');277 bytes.push(b'\n');
@@ -409,8 +389,6 @@ mod tests {
409 assert!(matches!(result, Err(ImageError::Registry { .. })));389 assert!(matches!(result, Err(ImageError::Registry { .. })));
410 }390 }
411 391
412- /// Pulls the real alpine image. Needs network access to Docker Hub.
413- /// Run with: cargo test -p forge-runner oci -- --ignored
414 #[tokio::test]392 #[tokio::test]
415 #[ignore]393 #[ignore]
416 async fn pulls_alpine_for_real() {394 async fn pulls_alpine_for_real() {
@@ -427,7 +405,6 @@ mod tests {
427 assert!(first.rootfs.join("bin/sh").symlink_metadata().is_ok());405 assert!(first.rootfs.join("bin/sh").symlink_metadata().is_ok());
428 assert!(first.env.iter().any(|e| e.starts_with("PATH=")));406 assert!(first.env.iter().any(|e| e.starts_with("PATH=")));
429 407
430- // A second ensure with the same digest reuses the unpacked rootfs.
431 let second = store408 let second = store
432 .ensure("alpine", None, &tx)409 .ensure("alpine", None, &tx)
433 .await410 .await
crates/forge-runner/src/oci/store.rsmodified+0 -43
@@ -1,5 +1,3 @@
1-//! On-disk layout of the image store, the metadata format, and garbage collection.
2-
3 use std::collections::HashSet;1 use std::collections::HashSet;
4 use std::fs;2 use std::fs;
5 use std::io::{self, Write};3 use std::io::{self, Write};
@@ -12,47 +10,35 @@ use sha2::{Digest, Sha256};
12 use super::{ImageError, PreparedImage};10 use super::{ImageError, PreparedImage};
13 use crate::sandbox::idmap::{IdMap, remove_tree};11 use crate::sandbox::idmap::{IdMap, remove_tree};
14 12
15-/// The default cap on the unpacked size of one image.
16 pub const DEFAULT_MAX_UNPACKED_BYTES: u64 = 20 * 1024 * 1024 * 1024;13 pub const DEFAULT_MAX_UNPACKED_BYTES: u64 = 20 * 1024 * 1024 * 1024;
17 14
18-/// Staging files and dirs older than this are assumed to be left behind by a crash and are removed.
19 const STALE_TEMP_AGE: Duration = Duration::from_secs(60 * 60);15 const STALE_TEMP_AGE: Duration = Duration::from_secs(60 * 60);
20-/// Name prefixes of staging entries: `tempfile`'s default prefix, and the unpack staging dirs.
21 const TEMP_PREFIXES: [&str; 2] = [".tmp", ".unpack-"];16 const TEMP_PREFIXES: [&str; 2] = [".tmp", ".unpack-"];
22 17
23-/// A cache of pulled and unpacked images rooted at one directory. See the module docs of
24-/// [`super`] for the layout.
25 pub struct ImageStore {18 pub struct ImageStore {
26 root: PathBuf,19 root: PathBuf,
27 max_unpacked_bytes: u64,20 max_unpacked_bytes: u64,
28- /// The id map that unpacking and removal run under. Single unless set by `with_idmap`.
29 pub(super) idmap: IdMap,21 pub(super) idmap: IdMap,
30- /// `forge-runner` itself, which runs `__sandbox-unpack` and `__sandbox-rm` in subuid mode.
31 pub(super) helper_exe: PathBuf,22 pub(super) helper_exe: PathBuf,
32 }23 }
33 24
34-/// What a garbage collection pass removed.
35 #[derive(Debug, Default, Clone, PartialEq, Eq)]25 #[derive(Debug, Default, Clone, PartialEq, Eq)]
36 pub struct GcStats {26 pub struct GcStats {
37 pub images_removed: u64,27 pub images_removed: u64,
38 pub blobs_removed: u64,28 pub blobs_removed: u64,
39- /// Staging leftovers (temp files and `.unpack-*` dirs) from crashed pulls.
40 pub temp_removed: u64,29 pub temp_removed: u64,
41 }30 }
42 31
43-/// The per-rootfs metadata stored in `meta/<hex>.json`.
44 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]32 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45 pub(super) struct ImageMeta {33 pub(super) struct ImageMeta {
46 pub digest: String,34 pub digest: String,
47 pub env: Vec<String>,35 pub env: Vec<String>,
48 pub working_dir: Option<String>,36 pub working_dir: Option<String>,
49 pub user: Option<String>,37 pub user: Option<String>,
50- /// Layer digests in order, as bare hex. Garbage collection keeps these blobs.
51 pub layers: Vec<String>,38 pub layers: Vec<String>,
52 }39 }
53 40
54 impl ImageStore {41 impl ImageStore {
55- /// A store rooted at `root`, with the default unpacked size cap.
56 pub fn new(root: PathBuf) -> Self {42 pub fn new(root: PathBuf) -> Self {
57 Self {43 Self {
58 root,44 root,
@@ -62,15 +48,11 @@ impl ImageStore {
62 }48 }
63 }49 }
64 50
65- /// Sets the cap on the unpacked size of one image, in bytes.
66 pub fn with_max_unpacked_bytes(mut self, bytes: u64) -> Self {51 pub fn with_max_unpacked_bytes(mut self, bytes: u64) -> Self {
67 self.max_unpacked_bytes = bytes;52 self.max_unpacked_bytes = bytes;
68 self53 self
69 }54 }
70 55
71- /// Unpacks under `map`. A subuid map unpacks through `helper_exe` (`__sandbox-unpack`), and its
72- /// rootfs dirs are named after the range, so a changed range unpacks again. A single map keeps
73- /// the plain `rootfs/<digest>` layout.
74 pub fn with_idmap(mut self, map: IdMap, helper_exe: PathBuf) -> Self {56 pub fn with_idmap(mut self, map: IdMap, helper_exe: PathBuf) -> Self {
75 self.idmap = map;57 self.idmap = map;
76 self.helper_exe = helper_exe;58 self.helper_exe = helper_exe;
@@ -95,8 +77,6 @@ impl ImageStore {
95 .join(rootfs_dir_name(&self.idmap, hex))77 .join(rootfs_dir_name(&self.idmap, hex))
96 }78 }
97 79
98- /// Removes a file, symlink or directory tree from the store. Trees go through `remove_tree`,
99- /// because subuid-owned files can only be removed by the helper.
100 pub(super) fn remove_entry(&self, path: &Path) -> io::Result<()> {80 pub(super) fn remove_entry(&self, path: &Path) -> io::Result<()> {
101 match fs::symlink_metadata(path) {81 match fs::symlink_metadata(path) {
102 Ok(meta) if meta.is_dir() => remove_tree(&self.idmap, path, &self.helper_exe),82 Ok(meta) if meta.is_dir() => remove_tree(&self.idmap, path, &self.helper_exe),
@@ -122,8 +102,6 @@ impl ImageStore {
122 self.root.join("tags").join(encode_tag(reference))102 self.root.join("tags").join(encode_tag(reference))
123 }103 }
124 104
125- /// Returns the image for `hex` when both its rootfs and its metadata are present. The rootfs
126- /// is only renamed into place once it is complete, so presence means complete.
127 pub(super) fn cached(&self, hex: &str) -> Result<Option<PreparedImage>, ImageError> {105 pub(super) fn cached(&self, hex: &str) -> Result<Option<PreparedImage>, ImageError> {
128 if !self.rootfs_path(hex).is_dir() || !self.meta_path(hex).is_file() {106 if !self.rootfs_path(hex).is_dir() || !self.meta_path(hex).is_file() {
129 return Ok(None);107 return Ok(None);
@@ -142,7 +120,6 @@ impl ImageStore {
142 }120 }
143 }121 }
144 122
145- /// The image that `reference` last resolved to, if it is still cached.
146 pub(super) fn cached_for_tag(123 pub(super) fn cached_for_tag(
147 &self,124 &self,
148 reference: &str,125 reference: &str,
@@ -164,7 +141,6 @@ impl ImageStore {
164 write_atomic(&self.meta_path(hex), &serde_json::to_vec(meta)?)141 write_atomic(&self.meta_path(hex), &serde_json::to_vec(meta)?)
165 }142 }
166 143
167- /// Marks the image as used now, for garbage collection.
168 pub(super) fn touch(&self, hex: &str) -> io::Result<()> {144 pub(super) fn touch(&self, hex: &str) -> io::Result<()> {
169 let path = self.stamp_path(hex);145 let path = self.stamp_path(hex);
170 if let Some(parent) = path.parent() {146 if let Some(parent) = path.parent() {
@@ -173,10 +149,6 @@ impl ImageStore {
173 fs::write(path, b"")149 fs::write(path, b"")
174 }150 }
175 151
176- /// Deletes unpacked rootfs directories and metadata that have not been used for `keep_days`,
177- /// then deletes layer blobs that no kept image refers to and that are older than `keep_days`.
178- /// Staging leftovers older than an hour are removed first. Images are locked while they are
179- /// checked, so a concurrent pull of the same image waits.
180 pub fn gc(&self, keep_days: u32) -> Result<GcStats, ImageError> {152 pub fn gc(&self, keep_days: u32) -> Result<GcStats, ImageError> {
181 let max_age = Duration::from_secs(u64::from(keep_days) * 86_400);153 let max_age = Duration::from_secs(u64::from(keep_days) * 86_400);
182 let now = SystemTime::now();154 let now = SystemTime::now();
@@ -229,8 +201,6 @@ impl ImageStore {
229 }201 }
230 }202 }
231 203
232-/// Opens (creating if needed) and exclusively locks a lock file. The lock is released when the
233-/// returned file is dropped.
234 pub(super) fn lock_file(path: &Path) -> io::Result<fs::File> {204 pub(super) fn lock_file(path: &Path) -> io::Result<fs::File> {
235 if let Some(parent) = path.parent() {205 if let Some(parent) = path.parent() {
236 fs::create_dir_all(parent)?;206 fs::create_dir_all(parent)?;
@@ -245,8 +215,6 @@ pub(super) fn lock_file(path: &Path) -> io::Result<fs::File> {
245 Ok(file)215 Ok(file)
246 }216 }
247 217
248-/// Writes `bytes` to `path` through a temp file in the same directory, so readers never see a
249-/// partial file.
250 pub(super) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), ImageError> {218 pub(super) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), ImageError> {
251 let dir = path219 let dir = path
252 .parent()220 .parent()
@@ -259,8 +227,6 @@ pub(super) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), ImageError>
259 Ok(())227 Ok(())
260 }228 }
261 229
262-/// Turns a reference into one file name. Letters, digits, `.` and `-` are kept, and every other
263-/// byte becomes `%xx`, so the encoding is injective. Long references are replaced by a hash.
264 fn encode_tag(reference: &str) -> String {230 fn encode_tag(reference: &str) -> String {
265 let mut out = String::with_capacity(reference.len());231 let mut out = String::with_capacity(reference.len());
266 for byte in reference.bytes() {232 for byte in reference.bytes() {
@@ -276,7 +242,6 @@ fn encode_tag(reference: &str) -> String {
276 out242 out
277 }243 }
278 244
279-/// The entries of `dir`, or none if it does not exist.
280 fn entries(dir: &Path) -> io::Result<Vec<PathBuf>> {245 fn entries(dir: &Path) -> io::Result<Vec<PathBuf>> {
281 match fs::read_dir(dir) {246 match fs::read_dir(dir) {
282 Ok(read) => read.map(|entry| entry.map(|e| e.path())).collect(),247 Ok(read) => read.map(|entry| entry.map(|e| e.path())).collect(),
@@ -299,8 +264,6 @@ fn older_than(time: SystemTime, now: SystemTime, max_age: Duration) -> bool {
299 now.duration_since(time).is_ok_and(|age| age > max_age)264 now.duration_since(time).is_ok_and(|age| age > max_age)
300 }265 }
301 266
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.
304 fn rootfs_dir_name(map: &IdMap, hex: &str) -> String {267 fn rootfs_dir_name(map: &IdMap, hex: &str) -> String {
305 match map.sub {268 match map.sub {
306 Some(s) => format!("{hex}-s{}-{}", s.uid_start, s.count),269 Some(s) => format!("{hex}-s{}-{}", s.uid_start, s.count),
@@ -362,7 +325,6 @@ mod tests {
362 format!("{n:064x}")325 format!("{n:064x}")
363 }326 }
364 327
365- /// Sets the mtime of a file or directory to `age` in the past.
366 fn set_age(path: &Path, age: Duration) {328 fn set_age(path: &Path, age: Duration) {
367 let when = SystemTime::now() - age;329 let when = SystemTime::now() - age;
368 fs::File::open(path)330 fs::File::open(path)
@@ -371,7 +333,6 @@ mod tests {
371 .expect("set_modified");333 .expect("set_modified");
372 }334 }
373 335
374- /// Writes an image that was last used just now, with the given layer blobs.
375 fn fresh_image(store: &ImageStore, hex: &str, layers: &[String]) {336 fn fresh_image(store: &ImageStore, hex: &str, layers: &[String]) {
376 fs::create_dir_all(store.rootfs_path(hex)).expect("rootfs");337 fs::create_dir_all(store.rootfs_path(hex)).expect("rootfs");
377 fs::write(store.rootfs_path(hex).join("file"), b"x").expect("file");338 fs::write(store.rootfs_path(hex).join("file"), b"x").expect("file");
@@ -431,11 +392,8 @@ mod tests {
431 assert!(store.rootfs_path(&fresh_img).is_dir());392 assert!(store.rootfs_path(&fresh_img).is_dir());
432 assert!(store.meta_path(&fresh_img).is_file());393 assert!(store.meta_path(&fresh_img).is_file());
433 394
434- // Stale but still referenced by a fresh image: kept.
435 assert!(store.blob_path(&shared).is_file());395 assert!(store.blob_path(&shared).is_file());
436- // Stale and only referenced by the removed image: removed.
437 assert!(!store.blob_path(&stale_layer).exists());396 assert!(!store.blob_path(&stale_layer).exists());
438- // Stale orphan: removed. Fresh orphan: kept.
439 assert!(!store.blob_path(&orphan_old).exists());397 assert!(!store.blob_path(&orphan_old).exists());
440 assert!(store.blob_path(&orphan_fresh).is_file());398 assert!(store.blob_path(&orphan_fresh).is_file());
441 }399 }
@@ -465,7 +423,6 @@ mod tests {
465 let stale_meta_tmp = meta.join(".tmpstale");423 let stale_meta_tmp = meta.join(".tmpstale");
466 fs::write(&stale_meta_tmp, b"{}").expect("meta tmp");424 fs::write(&stale_meta_tmp, b"{}").expect("meta tmp");
467 425
468- // A non-staging name in the same dir is never touched, however old it is.
469 let plain = root.join("rootfs/keep-me");426 let plain = root.join("rootfs/keep-me");
470 fs::create_dir_all(&plain).expect("plain");427 fs::create_dir_all(&plain).expect("plain");
471 set_age(&plain, two_hours);428 set_age(&plain, two_hours);
crates/forge-runner/src/oci/unpack.rsmodified+0 -69
@@ -1,19 +1,3 @@
1-//! Unpacks OCI image layers into a rootfs directory.
2-//!
3-//! Layers come from untrusted registries, so every rule here is about never writing outside the
4-//! rootfs. Paths are normalized to plain components first. Each parent component is then walked
5-//! one level at a time with `symlink_metadata`, and an entry is rejected when a parent is a
6-//! symlink or any other non-directory. Nothing is ever written through a link. Files are created
7-//! with `create_new`, after the old leaf has been removed, so an existing symlink is replaced
8-//! rather than followed.
9-//!
10-//! Ownership depends on [`Ownership`]. `Flatten` gives every file to the unpacking user, which is
11-//! what the single-uid user namespace expects. `Preserve` gives every entry the owner from its tar
12-//! header, with ids mapped into the user namespace. Either way setuid and setgid bits are stripped.
13-//! Extended attributes are never written, so file capabilities from the image do not apply. Device
14-//! nodes and fifos are skipped. Directories are kept owner-writable (`| 0o700`) while layers are
15-//! applied. `Preserve` sets their exact modes at the end, deepest first.
16-
17 use std::collections::{HashMap, HashSet};1 use std::collections::{HashMap, HashSet};
18 use std::ffi::{OsStr, OsString};2 use std::ffi::{OsStr, OsString};
19 use std::fs::{self, File, OpenOptions, Permissions};3 use std::fs::{self, File, OpenOptions, Permissions};
@@ -29,24 +13,19 @@ use tar::{Archive, EntryType};
29 const GZIP_MAGIC: &[u8] = &[0x1f, 0x8b];13 const GZIP_MAGIC: &[u8] = &[0x1f, 0x8b];
30 const ZSTD_MAGIC: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd];14 const ZSTD_MAGIC: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd];
31 const WHITEOUT_PREFIX: &[u8] = b".wh.";15 const WHITEOUT_PREFIX: &[u8] = b".wh.";
32-/// The opaque marker, after the `.wh.` prefix has been stripped.
33 const OPAQUE_MARKER: &[u8] = b".wh..opq";16 const OPAQUE_MARKER: &[u8] = b".wh..opq";
34 const COPY_BUF: usize = 64 * 1024;17 const COPY_BUF: usize = 64 * 1024;
35 18
36-/// Errors from unpacking. Entries that fail the path rules are not errors: they are counted in
37-/// `UnpackStats::rejected` and skipped.
38 #[derive(Debug, thiserror::Error)]19 #[derive(Debug, thiserror::Error)]
39 pub enum UnpackError {20 pub enum UnpackError {
40 #[error("unpack I/O error: {0}")]21 #[error("unpack I/O error: {0}")]
41 Io(#[from] std::io::Error),22 Io(#[from] std::io::Error),
42 #[error("unpacked size exceeds the {limit} byte limit")]23 #[error("unpacked size exceeds the {limit} byte limit")]
43 TooLarge { limit: u64 },24 TooLarge { limit: u64 },
44- /// The `__sandbox-unpack` helper failed. The message is its stderr, or a parse error.
45 #[error("unpack helper failed: {0}")]25 #[error("unpack helper failed: {0}")]
46 Helper(String),26 Helper(String),
47 }27 }
48 28
49-/// What unpacking did, for logging.
50 #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]29 #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
51 pub struct UnpackStats {30 pub struct UnpackStats {
52 pub files: u64,31 pub files: u64,
@@ -54,28 +33,18 @@ pub struct UnpackStats {
54 pub symlinks: u64,33 pub symlinks: u64,
55 pub hardlinks: u64,34 pub hardlinks: u64,
56 pub whiteouts: u64,35 pub whiteouts: u64,
57- /// Device nodes, fifos and entry types that are not supported.
58 pub skipped: u64,36 pub skipped: u64,
59- /// Entries whose path or link target failed the containment rules.
60 pub rejected: u64,37 pub rejected: u64,
61- /// Total bytes of regular file content written.
62 pub bytes: u64,38 pub bytes: u64,
63- /// Owner ids (uid or gid) at or above the map size, which became 0. Only set by `Preserve`.
64 pub remapped_ids: u64,39 pub remapped_ids: u64,
65 }40 }
66 41
67-/// How entries get their owner.
68 #[derive(Debug, Clone, Copy, PartialEq, Eq)]42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
69 pub enum Ownership {43 pub enum Ownership {
70- /// Every entry belongs to the unpacking user. This is the single-uid behaviour.
71 Flatten,44 Flatten,
72- /// Every entry gets its tar header owner, with ids mapped into a user namespace of `size` ids.
73- /// Ids `>= size` become 0 and are counted in `UnpackStats::remapped_ids`.
74 Preserve { size: u32 },45 Preserve { size: u32 },
75 }46 }
76 47
77-/// Maps a tar owner id into a user namespace of `size` ids. Ids below `size` are kept, and the
78-/// rest become 0. The flag is true when the id was changed.
79 pub fn map_id(id: u64, size: u32) -> (u32, bool) {48 pub fn map_id(id: u64, size: u32) -> (u32, bool) {
80 match u32::try_from(id) {49 match u32::try_from(id) {
81 Ok(id) if id < size => (id, false),50 Ok(id) if id < size => (id, false),
@@ -83,9 +52,6 @@ pub fn map_id(id: u64, size: u32) -> (u32, bool) {
83 }52 }
84 }53 }
85 54
86-/// Unpacks `layers` in order into `rootfs`, which must already exist and be empty. Each layer may
87-/// be a plain, gzip or zstd tar; the compression is detected from the first bytes. `max_bytes` caps
88-/// the total regular file content across all layers. `ownership` decides who owns the entries.
89 pub fn unpack_layers(55 pub fn unpack_layers(
90 rootfs: &Path,56 rootfs: &Path,
91 layers: &[PathBuf],57 layers: &[PathBuf],
@@ -115,12 +81,9 @@ struct Unpacker {
115 root: PathBuf,81 root: PathBuf,
116 limit: u64,82 limit: u64,
117 remaining: u64,83 remaining: u64,
118- /// Relative paths written by the current layer. Opaque markers keep these and drop the rest.
119 created: HashSet<PathBuf>,84 created: HashSet<PathBuf>,
120 ownership: Ownership,85 ownership: Ownership,
121- /// The owner of the entry being applied, with ids mapped. None when flattening.
122 owner: Option<(u32, u32)>,86 owner: Option<(u32, u32)>,
123- /// Exact directory modes for `Preserve`, keyed by path. Set by `finish_dir_modes`.
124 dir_modes: HashMap<PathBuf, u32>,87 dir_modes: HashMap<PathBuf, u32>,
125 stats: UnpackStats,88 stats: UnpackStats,
126 }89 }
@@ -146,7 +109,6 @@ impl Unpacker {
146 for entry in archive.entries()? {109 for entry in archive.entries()? {
147 let mut entry = entry?;110 let mut entry = entry?;
148 let kind = entry.header().entry_type();111 let kind = entry.header().entry_type();
149- // Keep the permission bits but never setuid, setgid. Sticky bit is kept.
150 let mode = entry.header().mode()? & 0o1777;112 let mode = entry.header().mode()? & 0o1777;
151 let size = entry.header().size()?;113 let size = entry.header().size()?;
152 let raw_path = entry.path_bytes().into_owned();114 let raw_path = entry.path_bytes().into_owned();
@@ -156,7 +118,6 @@ impl Unpacker {
156 continue;118 continue;
157 };119 };
158 if comps.is_empty() {120 if comps.is_empty() {
159- // "." or "./" is the rootfs itself.
160 continue;121 continue;
161 }122 }
162 self.owner = self.owner_of(entry.header())?;123 self.owner = self.owner_of(entry.header())?;
@@ -165,7 +126,6 @@ impl Unpacker {
165 Ok(())126 Ok(())
166 }127 }
167 128
168- /// The owner for an entry, with ids mapped. None when flattening.
169 fn owner_of(&mut self, header: &tar::Header) -> Result<Option<(u32, u32)>, UnpackError> {129 fn owner_of(&mut self, header: &tar::Header) -> Result<Option<(u32, u32)>, UnpackError> {
170 let Ownership::Preserve { size } = self.ownership else {130 let Ownership::Preserve { size } = self.ownership else {
171 return Ok(None);131 return Ok(None);
@@ -176,8 +136,6 @@ impl Unpacker {
176 Ok(Some((uid, gid)))136 Ok(Some((uid, gid)))
177 }137 }
178 138
179- /// Gives `path` the owner of the current entry, without following a symlink. Does nothing when
180- /// flattening.
181 fn own(&self, path: &Path) -> Result<(), UnpackError> {139 fn own(&self, path: &Path) -> Result<(), UnpackError> {
182 if let Some((uid, gid)) = self.owner {140 if let Some((uid, gid)) = self.owner {
183 lchown(path, Some(uid), Some(gid))?;141 lchown(path, Some(uid), Some(gid))?;
@@ -185,8 +143,6 @@ impl Unpacker {
185 Ok(())143 Ok(())
186 }144 }
187 145
188- /// Sets each directory to the exact mode it was last given, deepest first. A path that is no
189- /// longer a directory, because a later layer removed or replaced it, is skipped.
190 fn finish_dir_modes(&mut self) -> Result<(), UnpackError> {146 fn finish_dir_modes(&mut self) -> Result<(), UnpackError> {
191 let mut dirs: Vec<(PathBuf, u32)> = self.dir_modes.drain().collect();147 let mut dirs: Vec<(PathBuf, u32)> = self.dir_modes.drain().collect();
192 dirs.sort_by_key(|(path, _)| std::cmp::Reverse(path.components().count()));148 dirs.sort_by_key(|(path, _)| std::cmp::Reverse(path.components().count()));
@@ -240,8 +196,6 @@ impl Unpacker {
240 }196 }
241 self.own(&path)?;197 self.own(&path)?;
242 fs::set_permissions(&path, Permissions::from_mode(mode | 0o700))?;198 fs::set_permissions(&path, Permissions::from_mode(mode | 0o700))?;
243- // Only a directory whose mode is not already owner rwx needs its mode restored.
244- // A later layer may reset a directory an earlier one recorded, so drop the stale entry.
245 if matches!(self.ownership, Ownership::Preserve { .. }) {199 if matches!(self.ownership, Ownership::Preserve { .. }) {
246 if mode & 0o700 != 0o700 {200 if mode & 0o700 != 0o700 {
247 self.dir_modes.insert(path, mode);201 self.dir_modes.insert(path, mode);
@@ -272,7 +226,6 @@ impl Unpacker {
272 self.stats.files += 1;226 self.stats.files += 1;
273 }227 }
274 EntryType::Symlink => {228 EntryType::Symlink => {
275- // The target is stored as is. It is never followed while unpacking.
276 let Some(target) = link.filter(|target| !target.contains(&0)) else {229 let Some(target) = link.filter(|target| !target.contains(&0)) else {
277 return self.reject();230 return self.reject();
278 };231 };
@@ -287,7 +240,6 @@ impl Unpacker {
287 self.stats.symlinks += 1;240 self.stats.symlinks += 1;
288 }241 }
289 EntryType::Link => {242 EntryType::Link => {
290- // A hardlink must name a regular file inside the rootfs.
291 let Some(target) = link.and_then(normalize) else {243 let Some(target) = link.and_then(normalize) else {
292 return self.reject();244 return self.reject();
293 };245 };
@@ -311,21 +263,16 @@ impl Unpacker {
311 }263 }
312 remove_path(&path)?;264 remove_path(&path)?;
313 fs::hard_link(&source, &path)?;265 fs::hard_link(&source, &path)?;
314- // A hardlink shares its inode, so this also sets the owner of the source.
315 self.own(&path)?;266 self.own(&path)?;
316 self.created.insert(rel);267 self.created.insert(rel);
317 self.stats.hardlinks += 1;268 self.stats.hardlinks += 1;
318 }269 }
319- // Devices, fifos, sparse files and anything else. Skipped and counted.
320 _ => self.stats.skipped += 1,270 _ => self.stats.skipped += 1,
321 }271 }
322 Ok(())272 Ok(())
323 }273 }
324 274
325- /// Handles `.wh.<name>` (delete `<name>`) and `.wh..wh..opq` (clear the directory's contents
326- /// from earlier layers).
327 fn whiteout(&mut self, parents: &[OsString], name: &[u8]) -> Result<(), UnpackError> {275 fn whiteout(&mut self, parents: &[OsString], name: &[u8]) -> Result<(), UnpackError> {
328- // A whiteout under a missing or linked parent has nothing to delete.
329 let Some(dir) = self.resolve_dir(parents, false)? else {276 let Some(dir) = self.resolve_dir(parents, false)? else {
330 return Ok(());277 return Ok(());
331 };278 };
@@ -342,7 +289,6 @@ impl Unpacker {
342 Ok(())289 Ok(())
343 }290 }
344 291
345- /// Removes everything in `dir` that this layer did not write.
346 fn clear_dir(&mut self, dir: &Path, rel_dir: &Path) -> Result<(), UnpackError> {292 fn clear_dir(&mut self, dir: &Path, rel_dir: &Path) -> Result<(), UnpackError> {
347 for child in fs::read_dir(dir)? {293 for child in fs::read_dir(dir)? {
348 let child = child?;294 let child = child?;
@@ -355,9 +301,6 @@ impl Unpacker {
355 Ok(())301 Ok(())
356 }302 }
357 303
358- /// Walks `parents` from the root, one component at a time. Missing directories are created
359- /// when `create` is set, and are otherwise treated as absent. Returns `None` if any component
360- /// is a symlink or any other non-directory, or is missing with `create` unset.
361 fn resolve_dir(304 fn resolve_dir(
362 &mut self,305 &mut self,
363 parents: &[OsString],306 parents: &[OsString],
@@ -385,7 +328,6 @@ impl Unpacker {
385 Ok(Some(cur))328 Ok(Some(cur))
386 }329 }
387 330
388- /// Copies `src` to `dst`, failing as soon as the budget would be exceeded.
389 fn copy_capped<R: Read>(&mut self, src: &mut R, dst: &mut File) -> Result<(), UnpackError> {331 fn copy_capped<R: Read>(&mut self, src: &mut R, dst: &mut File) -> Result<(), UnpackError> {
390 use std::io::Write;332 use std::io::Write;
391 let mut buf = vec![0u8; COPY_BUF];333 let mut buf = vec![0u8; COPY_BUF];
@@ -409,8 +351,6 @@ impl Unpacker {
409 }351 }
410 }352 }
411 353
412-/// Turns an archive path into plain components. Returns `None` for absolute paths, paths with
413-/// `..`, and paths with NUL bytes. `.` components are dropped, so `./a` and `a` are the same.
414 fn normalize(raw: &[u8]) -> Option<Vec<OsString>> {354 fn normalize(raw: &[u8]) -> Option<Vec<OsString>> {
415 if raw.first() == Some(&b'/') || raw.contains(&0) {355 if raw.first() == Some(&b'/') || raw.contains(&0) {
416 return None;356 return None;
@@ -426,7 +366,6 @@ fn normalize(raw: &[u8]) -> Option<Vec<OsString>> {
426 Some(out)366 Some(out)
427 }367 }
428 368
429-/// Removes whatever is at `path` without following a symlink. Missing paths are fine.
430 pub(super) fn remove_path(path: &Path) -> std::io::Result<()> {369 pub(super) fn remove_path(path: &Path) -> std::io::Result<()> {
431 match fs::symlink_metadata(path) {370 match fs::symlink_metadata(path) {
432 Ok(meta) if meta.is_dir() => fs::remove_dir_all(path),371 Ok(meta) if meta.is_dir() => fs::remove_dir_all(path),
@@ -447,7 +386,6 @@ mod tests {
447 field[..value.len()].copy_from_slice(value.as_bytes());386 field[..value.len()].copy_from_slice(value.as_bytes());
448 }387 }
449 388
450- /// Appends one entry with a raw name, so tests can write names that `tar` would refuse.
451 fn put(389 fn put(
452 builder: &mut Builder<Vec<u8>>,390 builder: &mut Builder<Vec<u8>>,
453 kind: EntryType,391 kind: EntryType,
@@ -492,7 +430,6 @@ mod tests {
492 zstd::encode_all(bytes, 0).expect("zstd")430 zstd::encode_all(bytes, 0).expect("zstd")
493 }431 }
494 432
495- /// A temp dir with an empty `rootfs` and an `outside` dir that escapes must never reach.
496 struct Case {433 struct Case {
497 dir: tempfile::TempDir,434 dir: tempfile::TempDir,
498 rootfs: PathBuf,435 rootfs: PathBuf,
@@ -600,7 +537,6 @@ mod tests {
600 let stats = run(&c, &[first, second]).expect("unpack");537 let stats = run(&c, &[first, second]).expect("unpack");
601 assert!(!c.outside.join("passwd").exists());538 assert!(!c.outside.join("passwd").exists());
602 assert_eq!(stats.rejected, 1);539 assert_eq!(stats.rejected, 1);
603- // The link itself is still there, and is not replaced by a directory.
604 assert!(540 assert!(
605 fs::symlink_metadata(c.rootfs.join("a"))541 fs::symlink_metadata(c.rootfs.join("a"))
606 .expect("meta")542 .expect("meta")
@@ -708,13 +644,10 @@ mod tests {
708 file(b, "opt/.wh.app", b"");644 file(b, "opt/.wh.app", b"");
709 });645 });
710 let stats = run(&c, &[first, second]).expect("unpack");646 let stats = run(&c, &[first, second]).expect("unpack");
711- // Earlier file removed, sibling kept.
712 assert!(!c.rootfs.join("etc/old").exists());647 assert!(!c.rootfs.join("etc/old").exists());
713 assert!(c.rootfs.join("etc/keep").is_file());648 assert!(c.rootfs.join("etc/keep").is_file());
714- // Earlier directory tree removed.
715 assert!(!c.rootfs.join("opt/app").exists());649 assert!(!c.rootfs.join("opt/app").exists());
716 assert_eq!(stats.whiteouts, 2);650 assert_eq!(stats.whiteouts, 2);
717- // The whiteout markers themselves are never written.
718 assert!(!c.rootfs.join("etc/.wh.old").exists());651 assert!(!c.rootfs.join("etc/.wh.old").exists());
719 assert!(!c.rootfs.join("opt/.wh.app").exists());652 assert!(!c.rootfs.join("opt/.wh.app").exists());
720 }653 }
@@ -804,7 +737,6 @@ mod tests {
804 );737 );
805 }738 }
806 739
807- /// Writes one tar entry with an explicit owner and mode, and no data.
808 fn put_owned(740 fn put_owned(
809 builder: &mut Builder<Vec<u8>>,741 builder: &mut Builder<Vec<u8>>,
810 kind: EntryType,742 kind: EntryType,
@@ -829,7 +761,6 @@ mod tests {
829 761
830 #[test]762 #[test]
831 fn preserve_sets_owner_and_exact_directory_modes() {763 fn preserve_sets_owner_and_exact_directory_modes() {
832- // Owned by the test user, so the test can chown to it without privileges.
833 let c = case();764 let c = case();
834 let probe = c.dir.path().join("probe");765 let probe = c.dir.path().join("probe");
835 fs::write(&probe, b"").expect("probe");766 fs::write(&probe, b"").expect("probe");
crates/forge-runner/src/oom.rsmodified+0 -28
@@ -1,27 +1,8 @@
1-//! Out-of-memory kills inside a job's cgroup. The sandbox helper reads the cgroup's `memory.events`
2-//! when the job's init exits, before it deletes the cgroup, and prints one line on stderr. The
3-//! runner reads that line back and reports it when it finishes the job.
4-//!
5-//! Why the cgroup and not the exit code: when rustc is killed, cargo prints `(signal: 9, SIGKILL:
6-//! kill)` in the log and itself exits 101, so neither the job's exit code nor its message shows it.
7-//!
8-//! Kernel semantics (`Documentation/admin-guide/cgroup-v2.rst`): in `memory.events`, `oom` counts
9-//! how often the cgroup reached its limit and the OOM killer was invoked for it, and `oom_kill`
10-//! counts the processes of this cgroup that were killed by any kind of OOM killer. The victim's
11-//! cgroup is charged in `oom_kill_process`, so a victim of a host-wide OOM (global OOM killer,
12-//! nothing hit its own `memory.max`) is still counted in `oom_kill` of the cgroup it lived in, on
13-//! kernels since 4.13 that have the counter. `oom` stays 0 in that case, which is why both are
14-//! read and `oom_kill` is the one to trust. Both are hierarchical in `memory.events`, so a
15-//! process in a child cgroup counts too. A victim that was not in the job's cgroup at all (the
16-//! runner itself) is not counted, and nothing here can see it.
17-
18 use std::sync::Arc;1 use std::sync::Arc;
19 use std::sync::atomic::{AtomicU32, Ordering};2 use std::sync::atomic::{AtomicU32, Ordering};
20 3
21-/// The line the helper prints. It starts with the sandbox prefix, see `SANDBOX_PREFIX`.
22 pub const LINE_PREFIX: &str = "forge-sandbox: oom-events ";4 pub const LINE_PREFIX: &str = "forge-sandbox: oom-events ";
23 5
24-/// The `oom` and `oom_kill` counters of a job cgroup.
25 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]6 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26 pub struct OomEvents {7 pub struct OomEvents {
27 pub oom: u64,8 pub oom: u64,
@@ -29,7 +10,6 @@ pub struct OomEvents {
29 }10 }
30 11
31 impl OomEvents {12 impl OomEvents {
32- /// Reads the counters from the text of a `memory.events` file. Missing keys count as 0.
33 pub fn parse_memory_events(text: &str) -> Self {13 pub fn parse_memory_events(text: &str) -> Self {
34 let mut events = Self::default();14 let mut events = Self::default();
35 for line in text.lines() {15 for line in text.lines() {
@@ -47,22 +27,18 @@ impl OomEvents {
47 events27 events
48 }28 }
49 29
50- /// True when something in the job was OOM-killed or the cgroup hit its limit.
51 pub fn any(&self) -> bool {30 pub fn any(&self) -> bool {
52 self.oom > 0 || self.oom_kill > 031 self.oom > 0 || self.oom_kill > 0
53 }32 }
54 33
55- /// How many kills to report: `oom_kill`, or `oom` when only that one moved.
56 pub fn kills(&self) -> u32 {34 pub fn kills(&self) -> u32 {
57 u32::try_from(self.oom_kill.max(self.oom)).unwrap_or(u32::MAX)35 u32::try_from(self.oom_kill.max(self.oom)).unwrap_or(u32::MAX)
58 }36 }
59 37
60- /// The stderr line for the runner, without a newline.
61 pub fn to_line(&self) -> String {38 pub fn to_line(&self) -> String {
62 format!("{LINE_PREFIX}oom={} oom_kill={}", self.oom, self.oom_kill)39 format!("{LINE_PREFIX}oom={} oom_kill={}", self.oom, self.oom_kill)
63 }40 }
64 41
65- /// Reads a line written by [`OomEvents::to_line`].
66 pub fn from_line(line: &str) -> Option<Self> {42 pub fn from_line(line: &str) -> Option<Self> {
67 let rest = line.trim_end().strip_prefix(LINE_PREFIX)?;43 let rest = line.trim_end().strip_prefix(LINE_PREFIX)?;
68 let mut events = Self::default();44 let mut events = Self::default();
@@ -79,7 +55,6 @@ impl OomEvents {
79 }55 }
80 }56 }
81 57
82-/// Where an executor leaves the OOM kills it saw for a job. Cheap to clone and share.
83 #[derive(Clone, Debug, Default)]58 #[derive(Clone, Debug, Default)]
84 pub struct OomSink(Arc<AtomicU32>);59 pub struct OomSink(Arc<AtomicU32>);
85 60
@@ -90,7 +65,6 @@ impl OomSink {
90 }65 }
91 }66 }
92 67
93- /// The reported kills, or `None` when nothing was killed or the executor cannot tell.
94 pub fn kills(&self) -> Option<u32> {68 pub fn kills(&self) -> Option<u32> {
95 match self.0.load(Ordering::SeqCst) {69 match self.0.load(Ordering::SeqCst) {
96 0 => None,70 0 => None,
@@ -127,14 +101,12 @@ mod tests {
127 let sink = OomSink::default();101 let sink = OomSink::default();
128 sink.record(events);102 sink.record(events);
129 assert_eq!(sink.kills(), None);103 assert_eq!(sink.kills(), None);
130- // Older kernels have no counters at all.
131 assert!(!OomEvents::parse_memory_events("low 0\nmax 1\n").any());104 assert!(!OomEvents::parse_memory_events("low 0\nmax 1\n").any());
132 assert!(!OomEvents::parse_memory_events("").any());105 assert!(!OomEvents::parse_memory_events("").any());
133 }106 }
134 107
135 #[test]108 #[test]
136 fn a_host_wide_oom_shows_in_oom_kill_only() {109 fn a_host_wide_oom_shows_in_oom_kill_only() {
137- // The job's own limit was never reached, but its rustc was the global OOM victim.
138 let events = OomEvents::parse_memory_events("max 0\noom 0\noom_kill 1\n");110 let events = OomEvents::parse_memory_events("max 0\noom 0\noom_kill 1\n");
139 assert!(events.any());111 assert!(events.any());
140 assert_eq!(events.kills(), 1);112 assert_eq!(events.kills(), 1);
crates/forge-runner/src/pressure.rsmodified+0 -143
@@ -1,21 +1,3 @@
1-//! Reactive memory control. The runner puts every job cgroup inside one box cgroup
2-//! (`forge-jobs`) that is capped at the memory budget. When two or more jobs run and the box nears
3-//! its cap, the youngest job is frozen and its memory is pushed to swap, so the other job keeps
4-//! its RAM and nothing is OOM-killed. The parked job thaws when there is room again. When parking
5-//! does not work, the job is killed and queued again on the forge. A lone job is never paused: it
6-//! may use the whole box, and a real OOM there is reported as before (see [`crate::oom`]).
7-//!
8-//! Nothing here polls. The box's `memory.events` is watched with inotify (the `high` counter
9-//! moves the moment an allocation is held back by `memory.high`), the box's `memory.pressure` has
10-//! a PSI trigger as a second signal, and jobs starting and ending wake the controller too.
11-//!
12-//! `memory.high` is a brake that never lets go by itself: with swap off for the jobs, allocations
13-//! above it stall for minutes. So it is only set while 2+ jobs run unfrozen, and the controller
14-//! relaxes it the moment the stalled job is the only one left.
15-//!
16-//! The cgroup files are read and written through plain paths, so tests use a temp dir as a fake
17-//! cgroup.
18-
19 use std::fs::{self, File, OpenOptions};1 use std::fs::{self, File, OpenOptions};
20 use std::io::{self, Write};2 use std::io::{self, Write};
21 use std::os::fd::{AsFd, OwnedFd};3 use std::os::fd::{AsFd, OwnedFd};
@@ -35,36 +17,22 @@ use tokio_util::sync::CancellationToken;
35 use crate::executor::kill_cgroup;17 use crate::executor::kill_cgroup;
36 use crate::sandbox::{BOX_NAME, job_cgroup_base};18 use crate::sandbox::{BOX_NAME, job_cgroup_base};
37 19
38-/// Where cgroup2 is mounted.
39 const CGROUP_ROOT: &str = "/sys/fs/cgroup";20 const CGROUP_ROOT: &str = "/sys/fs/cgroup";
40-/// The controllers jobs need, enabled on the box and on its parent.
41 const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"];21 const CONTROLLERS: [&str; 3] = ["memory", "cpu", "pids"];
42-/// The PSI trigger: 150 ms of stall in a 2 s window. Unprivileged users need a multiple of 2 s.
43 const PSI_TRIGGER: &str = "some 150000 2000000";22 const PSI_TRIGGER: &str = "some 150000 2000000";
44-/// `memory.high` sits below the box cap by the larger of this and 5% of the cap.
45 const HIGH_MARGIN_MIN: u64 = 512 << 20;23 const HIGH_MARGIN_MIN: u64 = 512 << 20;
46-/// How hard a parked job's pages are pushed to swap.
47 const SWAPPINESS: u32 = 200;24 const SWAPPINESS: u32 = 200;
48-/// How many reclaim writes to try on a frozen job. One write may reclaim only part of it.
49 const RECLAIM_ATTEMPTS: u32 = 4;25 const RECLAIM_ATTEMPTS: u32 = 4;
50-/// How long a leftover job cgroup from an earlier runner gets to die at startup.
51 const LEFTOVER_POLLS: u32 = 50;26 const LEFTOVER_POLLS: u32 = 50;
52 const LEFTOVER_POLL: Duration = Duration::from_millis(100);27 const LEFTOVER_POLL: Duration = Duration::from_millis(100);
53-/// How long a pressure signal holds the gate shut. Pressure is a moment, not a state: without a
54-/// later look the gate would stay shut when the last signal came after the last job ended.
55 const PRESSURE_COOLDOWN: Duration = Duration::from_secs(10);28 const PRESSURE_COOLDOWN: Duration = Duration::from_secs(10);
56 29
57-/// What woke the controller.
58 #[derive(Clone, Copy, Debug, PartialEq, Eq)]30 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
59 pub enum Cause {31 pub enum Cause {
60- /// The box is short of memory: `high` moved in `memory.events`, or the PSI trigger fired.
61 Pressure,32 Pressure,
62- /// A job started or ended, or the box changed in a way that is no pressure signal.
63 Jobs,33 Jobs,
64 }34 }
65 35
66-// ----- pure rules -----
67-
68 fn field_u64(text: &str, key: &str) -> Option<u64> {36 fn field_u64(text: &str, key: &str) -> Option<u64> {
69 text.lines().find_map(|line| {37 text.lines().find_map(|line| {
70 let (k, v) = line.split_once(' ')?;38 let (k, v) = line.split_once(' ')?;
@@ -72,13 +40,10 @@ fn field_u64(text: &str, key: &str) -> Option<u64> {
72 })40 })
73 }41 }
74 42
75-/// The `high` counter of a `memory.events` text. Missing means 0.
76 pub fn parse_high(text: &str) -> u64 {43 pub fn parse_high(text: &str) -> u64 {
77 field_u64(text, "high").unwrap_or(0)44 field_u64(text, "high").unwrap_or(0)
78 }45 }
79 46
80-/// `memory.high` of the box, or `None` for `max`. Only set while two or more jobs run unfrozen:
81-/// a lone job runs up to the box's `memory.max`.
82 pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> {47 pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> {
83 if unfrozen < 2 {48 if unfrozen < 2 {
84 return None;49 return None;
@@ -87,7 +52,6 @@ pub fn high_value(unfrozen: usize, budget: u64) -> Option<u64> {
87 Some(budget.saturating_sub(margin).max(budget / 2))52 Some(budget.saturating_sub(margin).max(budget / 2))
88 }53 }
89 54
90-/// The job to park: the youngest, and only while at least two run.
91 pub fn pick_victim(seqs: &[u64]) -> Option<usize> {55 pub fn pick_victim(seqs: &[u64]) -> Option<usize> {
92 if seqs.len() < 2 {56 if seqs.len() < 2 {
93 return None;57 return None;
@@ -98,29 +62,21 @@ pub fn pick_victim(seqs: &[u64]) -> Option<usize> {
98 .map(|(i, _)| i)62 .map(|(i, _)| i)
99 }63 }
100 64
101-/// A parked job, as far as thaw choice cares.
102 #[derive(Clone, Copy, Debug, PartialEq, Eq)]65 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
103 pub struct Parked {66 pub struct Parked {
104 pub seq: u64,67 pub seq: u64,
105- /// Bytes of the job that sit in swap.
106 pub swap: u64,68 pub swap: u64,
107 }69 }
108 70
109-/// The parked job to thaw: the oldest, once the box has room for what is in its swap or nothing
110-/// else runs.
111 pub fn pick_thaw(parked: &[Parked], unfrozen_running: usize, headroom: u64) -> Option<usize> {71 pub fn pick_thaw(parked: &[Parked], unfrozen_running: usize, headroom: u64) -> Option<usize> {
112 let (index, oldest) = parked.iter().enumerate().min_by_key(|(_, p)| p.seq)?;72 let (index, oldest) = parked.iter().enumerate().min_by_key(|(_, p)| p.seq)?;
113 (unfrozen_running == 0 || headroom >= oldest.swap).then_some(index)73 (unfrozen_running == 0 || headroom >= oldest.swap).then_some(index)
114 }74 }
115 75
116-/// Whether the box is marked as under pressure after a pass. Pressure signals set it. Any other
117-/// wake clears it, unless the box still sits at `memory.high`.
118 pub fn hot_after(cause: Cause, over_high: bool, jobs: usize) -> bool {76 pub fn hot_after(cause: Cause, over_high: bool, jobs: usize) -> bool {
119- // An empty box has nothing to hold back, so nothing keeps the runner from claiming.
120 jobs > 0 && (cause == Cause::Pressure || over_high)77 jobs > 0 && (cause == Cause::Pressure || over_high)
121 }78 }
122 79
123-/// The admission gate: the runner claims a new job only while it is open.
124 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]80 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
125 pub struct Gate {81 pub struct Gate {
126 pub frozen: usize,82 pub frozen: usize,
@@ -133,15 +89,12 @@ impl Gate {
133 }89 }
134 }90 }
135 91
136-// ----- the jobs the controller knows -----
137-
138 #[derive(Default)]92 #[derive(Default)]
139 struct PauseClock {93 struct PauseClock {
140 total: Duration,94 total: Duration,
141 since: Option<Instant>,95 since: Option<Instant>,
142 }96 }
143 97
144-/// One registered job, shared between its runner task and the controller.
145 pub struct JobHandle {98 pub struct JobHandle {
146 id: String,99 id: String,
147 name: String,100 name: String,
@@ -151,7 +104,6 @@ pub struct JobHandle {
151 }104 }
152 105
153 impl JobHandle {106 impl JobHandle {
154- /// Appends a line to the job's log. A full or closed log drops it.
155 fn log_line(&self, line: &str) {107 fn log_line(&self, line: &str) {
156 let guard = self.log.lock().unwrap_or_else(PoisonError::into_inner);108 let guard = self.log.lock().unwrap_or_else(PoisonError::into_inner);
157 if let Some(tx) = guard.as_ref() {109 if let Some(tx) = guard.as_ref() {
@@ -161,7 +113,6 @@ impl JobHandle {
161 }113 }
162 }114 }
163 115
164- /// How long the job has spent frozen so far.
165 pub fn paused(&self) -> Duration {116 pub fn paused(&self) -> Duration {
166 let clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);117 let clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
167 clock.total + clock.since.map(|s| s.elapsed()).unwrap_or_default()118 clock.total + clock.since.map(|s| s.elapsed()).unwrap_or_default()
@@ -172,7 +123,6 @@ impl JobHandle {
172 clock.since.get_or_insert_with(Instant::now);123 clock.since.get_or_insert_with(Instant::now);
173 }124 }
174 125
175- /// Ends a pause and returns how long it lasted.
176 fn resume(&self) -> Duration {126 fn resume(&self) -> Duration {
177 let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);127 let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
178 let lasted = clock.since.take().map(|s| s.elapsed()).unwrap_or_default();128 let lasted = clock.since.take().map(|s| s.elapsed()).unwrap_or_default();
@@ -181,19 +131,16 @@ impl JobHandle {
181 }131 }
182 }132 }
183 133
184-/// A job's registration. Dropping it takes the job out of the controller's view.
185 pub struct Registration {134 pub struct Registration {
186 handle: Arc<JobHandle>,135 handle: Arc<JobHandle>,
187 owner: Arc<Pressure>,136 owner: Arc<Pressure>,
188 }137 }
189 138
190 impl Registration {139 impl Registration {
191- /// True when the controller killed the job to give it back to the queue.
192 pub fn requeued(&self) -> bool {140 pub fn requeued(&self) -> bool {
193 self.handle.requeued.load(Ordering::SeqCst)141 self.handle.requeued.load(Ordering::SeqCst)
194 }142 }
195 143
196- /// A handle for reading [`JobHandle::paused`] from another task.
197 pub fn pause_clock(&self) -> Arc<JobHandle> {144 pub fn pause_clock(&self) -> Arc<JobHandle> {
198 self.handle.clone()145 self.handle.clone()
199 }146 }
@@ -201,7 +148,6 @@ impl Registration {
201 148
202 impl Drop for Registration {149 impl Drop for Registration {
203 fn drop(&mut self) {150 fn drop(&mut self) {
204- // The log sender must go now, or the log shipper would wait for it.
205 *self151 *self
206 .handle152 .handle
207 .log153 .log
@@ -214,7 +160,6 @@ impl Drop for Registration {
214 struct Entry {160 struct Entry {
215 handle: Arc<JobHandle>,161 handle: Arc<JobHandle>,
216 seq: u64,162 seq: u64,
217- /// The job's cgroup, once the sandbox has created it.
218 dir: Option<PathBuf>,163 dir: Option<PathBuf>,
219 frozen: Option<Frozen>,164 frozen: Option<Frozen>,
220 }165 }
@@ -227,26 +172,19 @@ struct Frozen {
227 struct State {172 struct State {
228 entries: Vec<Entry>,173 entries: Vec<Entry>,
229 gate: Gate,174 gate: Gate,
230- /// The `memory.high` last written, to skip repeated writes.
231 high: Option<Option<u64>>,175 high: Option<Option<u64>>,
232 }176 }
233 177
234-/// The box and the controller of the jobs in it.
235 pub struct Pressure {178 pub struct Pressure {
236 dir: PathBuf,179 dir: PathBuf,
237 budget: AtomicU64,180 budget: AtomicU64,
238 state: Mutex<State>,181 state: Mutex<State>,
239 seq: AtomicU64,182 seq: AtomicU64,
240- /// Wakes the watcher: a job registered or ended.
241 kick: Notify,183 kick: Notify,
242- /// Wakes the claim loop: the gate may have changed.
243 changed: Notify,184 changed: Notify,
244 }185 }
245 186
246 impl Pressure {187 impl Pressure {
247- /// Creates the box and starts the watcher. Returns `None`, after one log line, when the host
248- /// can't do it: cgroup controllers not delegated, no inotify, and so on. The runner then
249- /// works as before, without the box and without pausing.
250 pub async fn start(budget: u64, shutdown: CancellationToken) -> Option<Arc<Self>> {188 pub async fn start(budget: u64, shutdown: CancellationToken) -> Option<Arc<Self>> {
251 let setup = tokio::task::spawn_blocking(move || {189 let setup = tokio::task::spawn_blocking(move || {
252 let base = job_cgroup_base().map_err(|e| e.to_string())?;190 let base = job_cgroup_base().map_err(|e| e.to_string())?;
@@ -292,25 +230,19 @@ impl Pressure {
292 }230 }
293 }231 }
294 232
295- /// The memory the box may use: the budget it was created with.
296 pub fn budget(&self) -> u64 {233 pub fn budget(&self) -> u64 {
297 self.budget.load(Ordering::SeqCst)234 self.budget.load(Ordering::SeqCst)
298 }235 }
299 236
300- /// Follows a changed memory budget: resizes the box's `memory.max` and `memory.swap.max` and
301- /// lets the controller recompute `memory.high`. Does nothing when the budget is the same.
302- /// Blocks while the kernel reclaims on a shrink, so call it off the async runtime.
303 pub fn resize(&self, budget: u64) {237 pub fn resize(&self, budget: u64) {
304 if self.budget.swap(budget, Ordering::SeqCst) == budget {238 if self.budget.swap(budget, Ordering::SeqCst) == budget {
305 return;239 return;
306 }240 }
307- // Growing: raise max first. Shrinking: lower high first (it is recomputed below).
308 for file in ["memory.max", "memory.swap.max"] {241 for file in ["memory.max", "memory.swap.max"] {
309 if let Err(e) = fs::write(self.dir.join(file), budget.to_string()) {242 if let Err(e) = fs::write(self.dir.join(file), budget.to_string()) {
310 tracing::warn!("cannot resize {file} of the box: {e}");243 tracing::warn!("cannot resize {file} of the box: {e}");
311 }244 }
312 }245 }
313- // Force the next pass to write memory.high for the new budget.
314 self.lock().high = None;246 self.lock().high = None;
315 self.kick.notify_one();247 self.kick.notify_one();
316 tracing::info!(248 tracing::info!(
@@ -323,7 +255,6 @@ impl Pressure {
323 self.state.lock().unwrap_or_else(PoisonError::into_inner)255 self.state.lock().unwrap_or_else(PoisonError::into_inner)
324 }256 }
325 257
326- /// Puts a job under control. `log` receives the pause and resume lines.
327 pub fn register(258 pub fn register(
328 self: &Arc<Self>,259 self: &Arc<Self>,
329 job_id: &str,260 job_id: &str,
@@ -357,19 +288,15 @@ impl Pressure {
357 self.kick.notify_one();288 self.kick.notify_one();
358 }289 }
359 290
360- /// Memory the box has left, counting reclaimable page cache as free. `None` when unreadable.
361 pub fn headroom(&self) -> Option<u64> {291 pub fn headroom(&self) -> Option<u64> {
362 let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget());292 let max = read_u64(&self.dir, "memory.max").unwrap_or(self.budget());
363 Some(max.saturating_sub(box_usage(&self.dir)?))293 Some(max.saturating_sub(box_usage(&self.dir)?))
364 }294 }
365 295
366- /// The admission gate as it is now: how many jobs are parked and whether the box is hot.
367 pub fn gate(&self) -> Gate {296 pub fn gate(&self) -> Gate {
368 self.lock().gate297 self.lock().gate
369 }298 }
370 299
371- /// Resolves once the runner may claim: no job is parked and the box is not under pressure.
372- /// Woken by the controller, never by a timer.
373 pub async fn wait_open(&self) {300 pub async fn wait_open(&self) {
374 loop {301 loop {
375 let notified = self.changed.notified();302 let notified = self.changed.notified();
@@ -383,7 +310,6 @@ impl Pressure {
383 }310 }
384 311
385 async fn watch(self: Arc<Self>, mut watcher: Watcher, shutdown: CancellationToken) {312 async fn watch(self: Arc<Self>, mut watcher: Watcher, shutdown: CancellationToken) {
386- // Set while the gate is hot: when no new signal came by then, the box is looked at again.
387 let mut recheck: Option<tokio::time::Instant> = None;313 let mut recheck: Option<tokio::time::Instant> = None;
388 loop {314 loop {
389 let cause = tokio::select! {315 let cause = tokio::select! {
@@ -411,19 +337,14 @@ impl Pressure {
411 }337 }
412 }338 }
413 339
414- /// One pass: park a job if the box is short of memory, thaw one if there is room, and set
415- /// `memory.high` for what runs now. Blocks, so it runs off the async runtime.
416 fn settle(&self, cause: Cause) {340 fn settle(&self, cause: Cause) {
417 let mut state = self.lock();341 let mut state = self.lock();
418- // A job given back and claimed again keeps its id, and the killed run's cgroup can still
419- // be there, so a directory another entry holds is not this entry's.
420 let mut taken: Vec<PathBuf> = state.entries.iter().filter_map(|e| e.dir.clone()).collect();342 let mut taken: Vec<PathBuf> = state.entries.iter().filter_map(|e| e.dir.clone()).collect();
421 for entry in &mut state.entries {343 for entry in &mut state.entries {
422 if entry.dir.is_none()344 if entry.dir.is_none()
423 && let Some(dir) = find_job_dir(&self.dir, &entry.handle.id, &taken)345 && let Some(dir) = find_job_dir(&self.dir, &entry.handle.id, &taken)
424 {346 {
425 taken.push(dir.clone());347 taken.push(dir.clone());
426- // A real OOM then takes the whole job, not one of its processes.
427 let _ = fs::write(dir.join("memory.oom.group"), "1");348 let _ = fs::write(dir.join("memory.oom.group"), "1");
428 entry.dir = Some(dir);349 entry.dir = Some(dir);
429 }350 }
@@ -479,9 +400,6 @@ impl Pressure {
479 })400 })
480 .collect();401 .collect();
481 let running = state.entries.iter().filter(|e| is_live(e)).count();402 let running = state.entries.iter().filter(|e| is_live(e)).count();
482- // A thawed job starts touching its pages again, so it needs room below the level where
483- // `memory.high` would hold two jobs back, plus a margin to grow. Otherwise it would be
484- // parked again at once.
485 let below_high = high_value(running + 1, self.budget()).unwrap_or(0);403 let below_high = high_value(running + 1, self.budget()).unwrap_or(0);
486 let headroom = box_usage(&self.dir)404 let headroom = box_usage(&self.dir)
487 .map_or(0, |usage| below_high.saturating_sub(usage))405 .map_or(0, |usage| below_high.saturating_sub(usage))
@@ -494,7 +412,6 @@ impl Pressure {
494 let Some(dir) = entry.dir.clone() else {412 let Some(dir) = entry.dir.clone() else {
495 return;413 return;
496 };414 };
497- // Swap stays where it is. Nothing new goes out, and pages come back as the job touches them.
498 let _ = fs::write(dir.join("memory.swap.max"), "0");415 let _ = fs::write(dir.join("memory.swap.max"), "0");
499 if let Err(e) = fs::write(dir.join("cgroup.freeze"), "0") {416 if let Err(e) = fs::write(dir.join("cgroup.freeze"), "0") {
500 tracing::warn!(job_id = %entry.handle.id, "cannot thaw job: {e}");417 tracing::warn!(job_id = %entry.handle.id, "cannot thaw job: {e}");
@@ -509,14 +426,10 @@ impl Pressure {
509 }426 }
510 }427 }
511 428
512-/// Whether the entry counts as running and unfrozen: it has a cgroup, is not parked and was not
513-/// killed for requeueing.
514 fn is_live(entry: &Entry) -> bool {429 fn is_live(entry: &Entry) -> bool {
515 entry.dir.is_some() && entry.frozen.is_none() && !entry.handle.requeued.load(Ordering::SeqCst)430 entry.dir.is_some() && entry.frozen.is_none() && !entry.handle.requeued.load(Ordering::SeqCst)
516 }431 }
517 432
518-/// Freezes the job and pushes its memory to swap. When that does not work, kills the job so the
519-/// forge queues it again.
520 fn park(entry: &mut Entry, waiting_for: &str) {433 fn park(entry: &mut Entry, waiting_for: &str) {
521 let Some(dir) = entry.dir.clone() else {434 let Some(dir) = entry.dir.clone() else {
522 return;435 return;
@@ -529,7 +442,6 @@ fn park(entry: &mut Entry, waiting_for: &str) {
529 give_back(entry, "the host has no swap room for it");442 give_back(entry, "the host has no swap room for it");
530 return;443 return;
531 }444 }
532- // The job's own cgroup may swap now. Its swap.max was 0 so it never swapped by itself.
533 let _ = fs::write(dir.join("memory.swap.max"), "max");445 let _ = fs::write(dir.join("memory.swap.max"), "max");
534 if let Err(e) = fs::write(dir.join("cgroup.freeze"), "1") {446 if let Err(e) = fs::write(dir.join("cgroup.freeze"), "1") {
535 tracing::warn!(job_id = %handle.id, "cannot freeze job: {e}");447 tracing::warn!(job_id = %handle.id, "cannot freeze job: {e}");
@@ -560,8 +472,6 @@ fn park(entry: &mut Entry, waiting_for: &str) {
560 entry.frozen = Some(Frozen { swap });472 entry.frozen = Some(Frozen { swap });
561 }473 }
562 474
563-/// Writes the reclaim request. A rejected `swappiness` key falls back to the plain amount. The
564-/// return code is not trusted: EAGAIN comes back on success too, so callers read `memory.current`.
565 fn reclaim(dir: &Path, bytes: u64) {475 fn reclaim(dir: &Path, bytes: u64) {
566 let file = dir.join("memory.reclaim");476 let file = dir.join("memory.reclaim");
567 match fs::write(&file, format!("{bytes} swappiness={SWAPPINESS}")) {477 match fs::write(&file, format!("{bytes} swappiness={SWAPPINESS}")) {
@@ -572,8 +482,6 @@ fn reclaim(dir: &Path, bytes: u64) {
572 }482 }
573 }483 }
574 484
575-/// Kills the job and marks it for requeueing. The job's task sees the mark and queues it again
576-/// instead of reporting a result.
577 fn give_back(entry: &mut Entry, why: &str) {485 fn give_back(entry: &mut Entry, why: &str) {
578 entry.handle.requeued.store(true, Ordering::SeqCst);486 entry.handle.requeued.store(true, Ordering::SeqCst);
579 entry.handle.log_line(&format!(487 entry.handle.log_line(&format!(
@@ -581,15 +489,11 @@ fn give_back(entry: &mut Entry, why: &str) {
581 ));489 ));
582 tracing::warn!(job_id = %entry.handle.id, "{why}, killing job to requeue it");490 tracing::warn!(job_id = %entry.handle.id, "{why}, killing job to requeue it");
583 if let Some(dir) = &entry.dir {491 if let Some(dir) = &entry.dir {
584- // A frozen cgroup is killed too, but thaw first so the kill takes effect at once.
585 let _ = fs::write(dir.join("cgroup.freeze"), "0");492 let _ = fs::write(dir.join("cgroup.freeze"), "0");
586 kill_cgroup(dir);493 kill_cgroup(dir);
587 }494 }
588 }495 }
589 496
590-// ----- cgroup files -----
591-
592-/// The job's cgroup under the box: `forge-job-<id>-<pid>`.
593 fn find_job_dir(box_dir: &Path, job_id: &str, taken: &[PathBuf]) -> Option<PathBuf> {497 fn find_job_dir(box_dir: &Path, job_id: &str, taken: &[PathBuf]) -> Option<PathBuf> {
594 let prefix = format!("forge-job-{job_id}-");498 let prefix = format!("forge-job-{job_id}-");
595 fs::read_dir(box_dir)499 fs::read_dir(box_dir)
@@ -600,7 +504,6 @@ fn find_job_dir(box_dir: &Path, job_id: &str, taken: &[PathBuf]) -> Option<PathB
600 .find(|path| !taken.contains(path))504 .find(|path| !taken.contains(path))
601 }505 }
602 506
603-/// A single-number cgroup file. `None` when missing or `max`.
604 fn read_u64(dir: &Path, file: &str) -> Option<u64> {507 fn read_u64(dir: &Path, file: &str) -> Option<u64> {
605 fs::read_to_string(dir.join(file)).ok()?.trim().parse().ok()508 fs::read_to_string(dir.join(file)).ok()?.trim().parse().ok()
606 }509 }
@@ -614,14 +517,11 @@ fn job_swap(dir: &Path) -> Option<u64> {
614 read_u64(dir, "memory.swap.current")517 read_u64(dir, "memory.swap.current")
615 }518 }
616 519
617-/// What the box really holds: its charge minus inactive page cache, which the kernel gives up
618-/// first. `None` when the charge is unreadable.
619 fn box_usage(dir: &Path) -> Option<u64> {520 fn box_usage(dir: &Path) -> Option<u64> {
620 let current = read_u64(dir, "memory.current")?;521 let current = read_u64(dir, "memory.current")?;
621 Some(current.saturating_sub(stat_field(dir, "inactive_file").unwrap_or(0)))522 Some(current.saturating_sub(stat_field(dir, "inactive_file").unwrap_or(0)))
622 }523 }
623 524
624-/// `SwapFree` of `/proc/meminfo` in bytes.
625 fn swap_free_bytes() -> Option<u64> {525 fn swap_free_bytes() -> Option<u64> {
626 let text = fs::read_to_string("/proc/meminfo").ok()?;526 let text = fs::read_to_string("/proc/meminfo").ok()?;
627 let line = text.lines().find(|l| l.starts_with("SwapFree:"))?;527 let line = text.lines().find(|l| l.starts_with("SwapFree:"))?;
@@ -641,10 +541,6 @@ fn format_duration(d: Duration) -> String {
641 }541 }
642 }542 }
643 543
644-// ----- the box -----
645-
646-/// Creates or adopts the box under `parent`, enables the controllers, and sets its limits. Job
647-/// cgroups left by a runner that died are killed and removed. Returns the box directory.
648 pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> {544 pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> {
649 let dir = parent.join(BOX_NAME);545 let dir = parent.join(BOX_NAME);
650 match fs::create_dir(&dir) {546 match fs::create_dir(&dir) {
@@ -659,14 +555,11 @@ pub fn create_box(parent: &Path, budget: u64) -> Result<PathBuf, String> {
659 fs::write(dir.join(file), value).map_err(|e| format!("cannot set {file} on the box: {e}"))555 fs::write(dir.join(file), value).map_err(|e| format!("cannot set {file} on the box: {e}"))
660 };556 };
661 set("memory.max", budget.to_string())?;557 set("memory.max", budget.to_string())?;
662- // Only a parked job swaps, and its own swap.max says when. The box allows it.
663 set("memory.swap.max", budget.to_string())?;558 set("memory.swap.max", budget.to_string())?;
664 set("memory.high", "max".to_owned())?;559 set("memory.high", "max".to_owned())?;
665 Ok(dir)560 Ok(dir)
666 }561 }
667 562
668-/// Kills and removes the job cgroups a previous runner left in the box. Frozen ones are thawed
669-/// first, or the kill would wait for them.
670 fn remove_leftovers(box_dir: &Path) {563 fn remove_leftovers(box_dir: &Path) {
671 let Ok(children) = fs::read_dir(box_dir) else {564 let Ok(children) = fs::read_dir(box_dir) else {
672 return;565 return;
@@ -687,7 +580,6 @@ fn remove_leftovers(box_dir: &Path) {
687 }580 }
688 }581 }
689 582
690-/// Makes sure `dir` passes the job controllers on to its children.
691 fn enable_controllers(dir: &Path) -> Result<(), String> {583 fn enable_controllers(dir: &Path) -> Result<(), String> {
692 let file = dir.join("cgroup.subtree_control");584 let file = dir.join("cgroup.subtree_control");
693 let have =585 let have =
@@ -709,11 +601,6 @@ fn enable_controllers(dir: &Path) -> Result<(), String> {
709 })601 })
710 }602 }
711 603
712-// ----- the watcher -----
713-
714-/// The watcher thread and its channel. The thread blocks in `poll(2)` on the inotify fd, the PSI
715-/// trigger and a stop pipe, with no timeout. Dropping the `Watcher` closes the write end of the
716-/// stop pipe, which wakes the thread and ends it.
717 struct Watcher {604 struct Watcher {
718 rx: mpsc::UnboundedReceiver<Cause>,605 rx: mpsc::UnboundedReceiver<Cause>,
719 psi_armed: bool,606 psi_armed: bool,
@@ -727,7 +614,6 @@ impl Watcher {
727 inotify614 inotify
728 .add_watch(&box_dir.join("memory.events"), AddWatchFlags::IN_MODIFY)615 .add_watch(&box_dir.join("memory.events"), AddWatchFlags::IN_MODIFY)
729 .map_err(|e| format!("watching memory.events: {e}"))?;616 .map_err(|e| format!("watching memory.events: {e}"))?;
730- // A new or removed job cgroup is how the controller learns where a job lives.
731 inotify617 inotify
732 .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE)618 .add_watch(box_dir, AddWatchFlags::IN_CREATE | AddWatchFlags::IN_DELETE)
733 .map_err(|e| format!("watching the box: {e}"))?;619 .map_err(|e| format!("watching the box: {e}"))?;
@@ -871,9 +757,7 @@ mod tests {
871 fn high_applies_only_to_two_or_more_unfrozen_jobs() {757 fn high_applies_only_to_two_or_more_unfrozen_jobs() {
872 assert_eq!(high_value(0, 6 * GIB), None);758 assert_eq!(high_value(0, 6 * GIB), None);
873 assert_eq!(high_value(1, 6 * GIB), None);759 assert_eq!(high_value(1, 6 * GIB), None);
874- // 5% of 6 GiB is under 512 MiB, so the minimum margin applies.
875 assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN));760 assert_eq!(high_value(2, 6 * GIB), Some(6 * GIB - HIGH_MARGIN_MIN));
876- // 5% of 20 GiB is 1 GiB.
877 assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB));761 assert_eq!(high_value(3, 20 * GIB), Some(19 * GIB));
878 assert_eq!(high_value(2, 256 << 20), Some(128 << 20));762 assert_eq!(high_value(2, 256 << 20), Some(128 << 20));
879 }763 }
@@ -896,10 +780,8 @@ mod tests {
896 },780 },
897 ];781 ];
898 assert_eq!(pick_thaw(&[], 0, 10 * GIB), None);782 assert_eq!(pick_thaw(&[], 0, 10 * GIB), None);
899- // The oldest is index 1 and needs 2 GiB.
900 assert_eq!(pick_thaw(&parked, 1, 3 * GIB), Some(1));783 assert_eq!(pick_thaw(&parked, 1, 3 * GIB), Some(1));
901 assert_eq!(pick_thaw(&parked, 1, GIB), None);784 assert_eq!(pick_thaw(&parked, 1, GIB), None);
902- // Nothing else runs: always thaw, whatever the headroom.
903 assert_eq!(pick_thaw(&parked, 0, 0), Some(1));785 assert_eq!(pick_thaw(&parked, 0, 0), Some(1));
904 }786 }
905 787
@@ -920,14 +802,12 @@ mod tests {
920 }802 }
921 .open()803 .open()
922 );804 );
923- // A pressure signal heats the box, a job event cools it unless it is still at high.
924 assert!(hot_after(Cause::Pressure, false, 1));805 assert!(hot_after(Cause::Pressure, false, 1));
925 assert!(!hot_after(Cause::Jobs, false, 1));806 assert!(!hot_after(Cause::Jobs, false, 1));
926 assert!(hot_after(Cause::Jobs, true, 1));807 assert!(hot_after(Cause::Jobs, true, 1));
927 assert!(!hot_after(Cause::Pressure, false, 0));808 assert!(!hot_after(Cause::Pressure, false, 0));
928 }809 }
929 810
930- /// A fake box: a temp dir with the files the controller reads.
931 fn fake_box(budget: u64) -> (tempfile::TempDir, Arc<Pressure>) {811 fn fake_box(budget: u64) -> (tempfile::TempDir, Arc<Pressure>) {
932 let tmp = tempfile::tempdir().expect("tempdir");812 let tmp = tempfile::tempdir().expect("tempdir");
933 let dir = tmp.path().to_path_buf();813 let dir = tmp.path().to_path_buf();
@@ -973,7 +853,6 @@ mod tests {
973 assert!(!dir.join("cgroup.freeze").exists());853 assert!(!dir.join("cgroup.freeze").exists());
974 assert!(rx.try_recv().is_err());854 assert!(rx.try_recv().is_err());
975 assert!(!pressure.lock().gate.open());855 assert!(!pressure.lock().gate.open());
976- // The job ending cools the box.
977 drop(a);856 drop(a);
978 pressure.settle(Cause::Jobs);857 pressure.settle(Cause::Jobs);
979 assert!(pressure.lock().gate.open());858 assert!(pressure.lock().gate.open());
@@ -981,7 +860,6 @@ mod tests {
981 860
982 #[test]861 #[test]
983 fn a_job_that_cannot_be_parked_is_killed_for_requeue() {862 fn a_job_that_cannot_be_parked_is_killed_for_requeue() {
984- // In a fake cgroup memory.current never drops, so parking fails the way a full swap does.
985 let (tmp, pressure) = fake_box(6 * GIB);863 let (tmp, pressure) = fake_box(6 * GIB);
986 let (tx_a, _rx_a) = mpsc::channel(8);864 let (tx_a, _rx_a) = mpsc::channel(8);
987 let (tx_b, mut rx_b) = mpsc::channel(8);865 let (tx_b, mut rx_b) = mpsc::channel(8);
@@ -989,11 +867,9 @@ mod tests {
989 let b = pressure.register("b", "test", tx_b);867 let b = pressure.register("b", "test", tx_b);
990 fake_job(tmp.path(), "a", 2 * GIB);868 fake_job(tmp.path(), "a", 2 * GIB);
991 let dir_b = fake_job(tmp.path(), "b", 2 * GIB);869 let dir_b = fake_job(tmp.path(), "b", 2 * GIB);
992- // A tiny anon size, so the host's real SwapFree does not decide this test.
993 fs::write(dir_b.join("memory.stat"), "anon 1\n").expect("stat");870 fs::write(dir_b.join("memory.stat"), "anon 1\n").expect("stat");
994 pressure.settle(Cause::Jobs);871 pressure.settle(Cause::Jobs);
995 pressure.settle(Cause::Pressure);872 pressure.settle(Cause::Pressure);
996- // The youngest job is the victim, the older one keeps running.
997 assert!(b.requeued());873 assert!(b.requeued());
998 assert!(!a.requeued());874 assert!(!a.requeued());
999 assert_eq!(875 assert_eq!(
@@ -1006,7 +882,6 @@ mod tests {
1006 }882 }
1007 assert!(lines.contains("paused: memory pressure, waiting for build"));883 assert!(lines.contains("paused: memory pressure, waiting for build"));
1008 assert!(lines.contains("run it again later"));884 assert!(lines.contains("run it again later"));
1009- // A killed job no longer counts as running, so memory.high relaxes.
1010 assert_eq!(885 assert_eq!(
1011 fs::read_to_string(tmp.path().join("memory.high")).expect("high"),886 fs::read_to_string(tmp.path().join("memory.high")).expect("high"),
1012 "max"887 "max"
@@ -1026,7 +901,6 @@ mod tests {
1026 assert!(lasted > Duration::ZERO);901 assert!(lasted > Duration::ZERO);
1027 assert!(reg.handle.paused() >= lasted);902 assert!(reg.handle.paused() >= lasted);
1028 drop(reg);903 drop(reg);
1029- // The sender is gone with the registration, so the log shipper can finish.
1030 assert!(matches!(904 assert!(matches!(
1031 rx.try_recv(),905 rx.try_recv(),
1032 Err(mpsc::error::TryRecvError::Disconnected)906 Err(mpsc::error::TryRecvError::Disconnected)
@@ -1042,7 +916,6 @@ mod tests {
1042 fs::write(parent.join(BOX_NAME).join("cgroup.subtree_control"), "").expect("box");916 fs::write(parent.join(BOX_NAME).join("cgroup.subtree_control"), "").expect("box");
1043 let dir = create_box(parent, 4 * GIB).expect("box");917 let dir = create_box(parent, 4 * GIB).expect("box");
1044 assert_eq!(dir, parent.join(BOX_NAME));918 assert_eq!(dir, parent.join(BOX_NAME));
1045- // The fake files stand in for the kernel: the write replaced them with the new text.
1046 assert_eq!(919 assert_eq!(
1047 fs::read_to_string(dir.join("memory.max")).expect("max"),920 fs::read_to_string(dir.join("memory.max")).expect("max"),
1048 (4 * GIB).to_string()921 (4 * GIB).to_string()
@@ -1059,7 +932,6 @@ mod tests {
1059 fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"),932 fs::read_to_string(parent.join("cgroup.subtree_control")).expect("parent"),
1060 "+cpu"933 "+cpu"
1061 );934 );
1062- // A second call adopts the existing box.
1063 assert!(create_box(parent, 4 * GIB).is_ok());935 assert!(create_box(parent, 4 * GIB).is_ok());
1064 }936 }
1065 937
@@ -1082,9 +954,6 @@ mod tests {
1082 .expect("join");954 .expect("join");
1083 }955 }
1084 956
1085- /// Needs a delegated memory controller, so it only runs on request:
1086- /// `cargo test -p forge-runner real_box -- --ignored`. Builds a real box next to this
1087- /// process, checks the watcher can arm inotify and the PSI trigger, and removes the box.
1088 #[tokio::test]957 #[tokio::test]
1089 #[ignore = "needs delegated cgroup v2 controllers"]958 #[ignore = "needs delegated cgroup v2 controllers"]
1090 async fn real_box_starts_and_reports_headroom() {959 async fn real_box_starts_and_reports_headroom() {
@@ -1096,13 +965,10 @@ mod tests {
1096 assert!(pressure.headroom().is_some());965 assert!(pressure.headroom().is_some());
1097 pressure.wait_open().await;966 pressure.wait_open().await;
1098 shutdown.cancel();967 shutdown.cancel();
1099- // The watcher is gone once cancelled; the empty box can be removed.
1100 tokio::time::sleep(Duration::from_millis(100)).await;968 tokio::time::sleep(Duration::from_millis(100)).await;
1101 let _ = fs::remove_dir(&pressure.dir);969 let _ = fs::remove_dir(&pressure.dir);
1102 }970 }
1103 971
1104- /// Python allocator for the end-to-end test: waits for "go", touches `mib` MiB in 50 MiB
1105- /// steps, sleeps between steps, then re-reads everything and checks a checksum.
1106 const ALLOCATOR: &str = r#"972 const ALLOCATOR: &str = r#"
1107 import sys, time, hashlib973 import sys, time, hashlib
1108 mib = int(sys.argv[1]); step = 50974 mib = int(sys.argv[1]); step = 50
@@ -1128,10 +994,6 @@ print("ok")
1128 bytes.unwrap_or(0) >> 20994 bytes.unwrap_or(0) >> 20
1129 }995 }
1130 996
1131- /// End to end on a real box: two allocators of ~700 MiB under a 1 GiB budget. The youngest is
1132- /// frozen and parked in swap, the first completes, the parked one thaws and completes with its
1133- /// data intact, and nothing is OOM-killed. Needs delegated cgroup controllers, swap and
1134- /// python3: `cargo test -p forge-runner real_two_jobs -- --ignored --nocapture`.
1135 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]997 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1136 #[ignore = "needs delegated cgroup v2 controllers, swap and python3"]998 #[ignore = "needs delegated cgroup v2 controllers, swap and python3"]
1137 async fn real_two_jobs_one_is_parked_in_swap_and_both_finish() {999 async fn real_two_jobs_one_is_parked_in_swap_and_both_finish() {
@@ -1145,7 +1007,6 @@ print("ok")
1145 eprintln!("no delegated memory controller, skipping");1007 eprintln!("no delegated memory controller, skipping");
1146 return;1008 return;
1147 };1009 };
1148- // The PSI trigger arms on the real box.
1149 let probe = Watcher::open(&pressure.dir).expect("watcher");1010 let probe = Watcher::open(&pressure.dir).expect("watcher");
1150 let psi_armed = probe.psi_armed;1011 let psi_armed = probe.psi_armed;
1151 drop(probe);1012 drop(probe);
@@ -1176,11 +1037,9 @@ print("ok")
1176 let mut stdin = child.stdin.take().expect("stdin");1037 let mut stdin = child.stdin.take().expect("stdin");
1177 stdin.write_all(b"go\n").await.expect("go");1038 stdin.write_all(b"go\n").await.expect("go");
1178 jobs.push((id, dir, child, Some(registration), stdin));1039 jobs.push((id, dir, child, Some(registration), stdin));
1179- // The second job starts a little later, so it is the youngest and the other has grown.
1180 tokio::time::sleep(Duration::from_secs(2)).await;1040 tokio::time::sleep(Duration::from_secs(2)).await;
1181 }1041 }
1182 1042
1183- // Watch both jobs until they end.
1184 let mut parked_seen = false;1043 let mut parked_seen = false;
1185 let mut before_park = 0;1044 let mut before_park = 0;
1186 let mut at_park = (0, 0);1045 let mut at_park = (0, 0);
@@ -1199,7 +1058,6 @@ print("ok")
1199 {1058 {
1200 eprintln!("{} job {id} exited: {status}", started.elapsed().as_secs());1059 eprintln!("{} job {id} exited: {status}", started.elapsed().as_secs());
1201 results[i] = Some(status);1060 results[i] = Some(status);
1202- // Like the runner: the finished job leaves the controller, which thaws the other.
1203 drop(registration.take());1061 drop(registration.take());
1204 }1062 }
1205 if i == 1 && results[i].is_none() {1063 if i == 1 && results[i].is_none() {
@@ -1249,7 +1107,6 @@ print("ok")
1249 let box_events = fs::read_to_string(pressure.dir.join("memory.events")).unwrap_or_default();1107 let box_events = fs::read_to_string(pressure.dir.join("memory.events")).unwrap_or_default();
1250 eprintln!("box memory.events: {}", box_events.replace('\n', " "));1108 eprintln!("box memory.events: {}", box_events.replace('\n', " "));
1251 1109
1252- // Clean up before asserting, so a failure leaves no cgroups behind.
1253 shutdown.cancel();1110 shutdown.cancel();
1254 for (_, dir, mut child, registration, _) in jobs {1111 for (_, dir, mut child, registration, _) in jobs {
1255 let _ = child.start_kill();1112 let _ = child.start_kill();
crates/forge-runner/src/restart.rsmodified+0 -19
@@ -1,9 +1,3 @@
1-//! Restart on request. An admin can ask a runner to restart from the forge's web UI. The request
2-//! arrives in a claim answer or a heartbeat answer. The runner then stops claiming, waits for or
3-//! cancels its jobs, and ends its loop with [`crate::runner::RunEnd::Restart`]. The caller exits
4-//! with [`crate::update::RESTART_EXIT_CODE`], the same way a self-update ends, so the supervisor
5-//! (systemd `Restart=on-failure`) starts the binary again. Nothing here polls.
6-
7 use std::sync::OnceLock;1 use std::sync::OnceLock;
8 use std::sync::atomic::{AtomicBool, Ordering};2 use std::sync::atomic::{AtomicBool, Ordering};
9 use std::sync::{Mutex, PoisonError};3 use std::sync::{Mutex, PoisonError};
@@ -11,18 +5,14 @@ use std::sync::{Mutex, PoisonError};
11 use forge_ci::proto::RestartMode;5 use forge_ci::proto::RestartMode;
12 use tokio::sync::Notify;6 use tokio::sync::Notify;
13 7
14-/// A restart request seen from the forge, shared by the claim loop and the job heartbeats.
15 #[derive(Default)]8 #[derive(Default)]
16 pub struct RestartState {9 pub struct RestartState {
17 mode: Mutex<Option<RestartMode>>,10 mode: Mutex<Option<RestartMode>>,
18 wake: Notify,11 wake: Notify,
19- /// Set once the running jobs were cancelled for a `now` restart.
20 cancelled: AtomicBool,12 cancelled: AtomicBool,
21 }13 }
22 14
23 impl RestartState {15 impl RestartState {
24- /// Records what the forge said. `None` changes nothing, because a request cannot be taken
25- /// back from the runner's side. `drain` never replaces `now`. Wakes the loop on a change.
26 pub fn observe(&self, said: Option<RestartMode>) {16 pub fn observe(&self, said: Option<RestartMode>) {
27 let Some(said) = said else { return };17 let Some(said) = said else { return };
28 let mut mode = self.mode.lock().unwrap_or_else(PoisonError::into_inner);18 let mut mode = self.mode.lock().unwrap_or_else(PoisonError::into_inner);
@@ -40,7 +30,6 @@ impl RestartState {
40 *self.mode.lock().unwrap_or_else(PoisonError::into_inner)30 *self.mode.lock().unwrap_or_else(PoisonError::into_inner)
41 }31 }
42 32
43- /// Resolves after the pending request changed.
44 pub async fn changed(&self) {33 pub async fn changed(&self) {
45 self.wake.notified().await;34 self.wake.notified().await;
46 }35 }
@@ -49,26 +38,19 @@ impl RestartState {
49 self.cancelled.store(true, Ordering::SeqCst);38 self.cancelled.store(true, Ordering::SeqCst);
50 }39 }
51 40
52- /// Whether running jobs were cancelled for a `now` restart.
53 pub fn jobs_cancelled(&self) -> bool {41 pub fn jobs_cancelled(&self) -> bool {
54 self.cancelled.load(Ordering::SeqCst)42 self.cancelled.load(Ordering::SeqCst)
55 }43 }
56 }44 }
57 45
58-/// What the claim loop does next about a restart request.
59 #[derive(Clone, Copy, Debug, PartialEq, Eq)]46 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
60 pub enum Step {47 pub enum Step {
61- /// No request: claim as usual.
62 Proceed,48 Proceed,
63- /// Cancel the running jobs, then wait for them.
64 CancelJobs,49 CancelJobs,
65- /// Claim nothing and wait for a running job to end.
66 WaitForJobs,50 WaitForJobs,
67- /// Nothing is running: leave the loop so the process restarts.
68 Restart,51 Restart,
69 }52 }
70 53
71-/// The drain-then-restart decision. `cancelled` says whether the jobs were already cancelled.
72 pub fn decide(pending: Option<RestartMode>, running: usize, cancelled: bool) -> Step {54 pub fn decide(pending: Option<RestartMode>, running: usize, cancelled: bool) -> Step {
73 match pending {55 match pending {
74 None => Step::Proceed,56 None => Step::Proceed,
@@ -78,7 +60,6 @@ pub fn decide(pending: Option<RestartMode>, running: usize, cancelled: bool) ->
78 }60 }
79 }61 }
80 62
81-/// An id that is new for every process start. The forge sees a restart when it changes.
82 pub fn boot_id() -> &'static str {63 pub fn boot_id() -> &'static str {
83 static ID: OnceLock<String> = OnceLock::new();64 static ID: OnceLock<String> = OnceLock::new();
84 ID.get_or_init(|| {65 ID.get_or_init(|| {
crates/forge-runner/src/sandbox/exec.rsmodified+0 -12
@@ -1,10 +1,3 @@
1-//! The container's executor. It installs the seccomp filter, then execs the job.
2-//!
3-//! This replaces libcontainer's `DefaultExecutor::exec`, which does the same exec without a
4-//! filter. libcontainer runs the executor in the init process after the namespaces, mounts and
5-//! `no_new_privileges` are set up, and right before the job starts. `seccompiler::apply_filter`
6-//! also sets `PR_SET_NO_NEW_PRIVS` itself, so an unprivileged install works.
7-
8 use std::ffi::CString;1 use std::ffi::CString;
9 2
10 use libcontainer::workload::default::DefaultExecutor;3 use libcontainer::workload::default::DefaultExecutor;
@@ -13,8 +6,6 @@ use nix::unistd;
13 use oci_spec::runtime::Spec;6 use oci_spec::runtime::Spec;
14 use seccompiler::BpfProgram;7 use seccompiler::BpfProgram;
15 8
16-/// Installs `filter` and execs the spec's process. The filter is built by the helper before the
17-/// container forks, so this only installs it.
18 #[derive(Clone)]9 #[derive(Clone)]
19 pub struct FilteredExecutor {10 pub struct FilteredExecutor {
20 filter: BpfProgram,11 filter: BpfProgram,
@@ -34,13 +25,10 @@ impl Executor for FilteredExecutor {
34 }25 }
35 26
36 fn validate(&self, spec: &Spec) -> Result<(), ExecutorValidationError> {27 fn validate(&self, spec: &Spec) -> Result<(), ExecutorValidationError> {
37- // The same checks as libcontainer's default executor: the process exists in PATH.
38 DefaultExecutor {}.validate(spec)28 DefaultExecutor {}.validate(spec)
39 }29 }
40 }30 }
41 31
42-/// Replaces the process with `args[0]`, as libcontainer's default executor does. It returns only
43-/// on failure.
44 fn exec_process(spec: &Spec) -> Result<(), ExecutorError> {32 fn exec_process(spec: &Spec) -> Result<(), ExecutorError> {
45 let args = spec33 let args = spec
46 .process()34 .process()
crates/forge-runner/src/sandbox/helper.rsmodified+0 -88
@@ -1,27 +1,3 @@
1-//! The sandbox helper: the body of `forge-runner __sandbox`.
2-//!
3-//! The process is single-threaded and has no tokio runtime, because libcontainer forks and
4-//! clones. It reads one [`SandboxRequest`] from stdin, prepares the rootfs, creates and starts a
5-//! container, and waits for it. Its stdout and stderr are the container's, so the runner just
6-//! forwards them.
7-//!
8-//! Setup happens in this order:
9-//! 1. Enter a user namespace with the request's [`IdMap`](super::idmap::IdMap): root is the
10-//! runner's uid, and in subuid mode container ids `1..=n` are the subordinate range. The
11-//! overlay mount needs CAP_SYS_ADMIN in a user namespace that owns the mount namespace.
12-//! A job with network gets its own network namespace too, connected by pasta (see
13-//! [`net`](super::net)).
14-//! 2. An overlay mount of the image rootfs. If that fails, the rootfs is copied instead.
15-//! 3. The OCI spec is written to `bundle/config.json` (0600) and libcontainer builds the
16-//! container from it. The file is deleted right after `build()`, since libcontainer has
17-//! read it by then.
18-//! 4. The container starts and the helper waits. It sleeps in `poll` on a self-pipe that SIGTERM,
19-//! SIGINT and SIGCHLD write to, so it wakes as soon as one arrives. On SIGTERM or SIGINT the
20-//! container is killed and deleted. The exit code is the job's.
21-//!
22-//! Exit codes: the job's code, 128 + signal if the job was signalled, or 125 for a sandbox setup
23-//! failure. A setup failure prints `forge-sandbox: <reason>` on stderr.
24-
25 use std::fs::{self, OpenOptions};1 use std::fs::{self, OpenOptions};
26 use std::io::{self, Read, Write};2 use std::io::{self, Read, Write};
27 use std::os::fd::AsFd;3 use std::os::fd::AsFd;
@@ -52,11 +28,9 @@ use super::spec::{HOSTNAME, build_spec};
52 use super::{SandboxError, SandboxRequest};28 use super::{SandboxError, SandboxRequest};
53 use crate::workspace::validate_job_id;29 use crate::workspace::validate_job_id;
54 30
55-/// Exit code for a sandbox setup failure. The runner maps it to a sandbox error.
56 pub const EXIT_SETUP_FAILED: i32 = 125;31 pub const EXIT_SETUP_FAILED: i32 = 125;
57 const HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n";32 const HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n";
58 33
59-/// Entry point for `forge-runner __sandbox`. Returns the process exit code.
60 pub fn helper_main() -> i32 {34 pub fn helper_main() -> i32 {
61 if std::env::var_os("RUST_LOG").is_some() {35 if std::env::var_os("RUST_LOG").is_some() {
62 let _ = tracing_subscriber::fmt()36 let _ = tracing_subscriber::fmt()
@@ -73,13 +47,11 @@ pub fn helper_main() -> i32 {
73 }47 }
74 }48 }
75 49
76-/// The directories under `job_dir` that the helper uses.
77 struct Layout {50 struct Layout {
78 job_dir: PathBuf,51 job_dir: PathBuf,
79 bundle: PathBuf,52 bundle: PathBuf,
80 state: PathBuf,53 state: PathBuf,
81 etc: PathBuf,54 etc: PathBuf,
82- /// Bind mounted at `/tmp`: on the runner's disk, so temp files do not count as job memory.
83 tmp: PathBuf,55 tmp: PathBuf,
84 upper: PathBuf,56 upper: PathBuf,
85 work: PathBuf,57 work: PathBuf,
@@ -132,9 +104,6 @@ fn run() -> Result<i32, SandboxError> {
132 result104 result
133 }105 }
134 106
135-/// Sets every entry under `workspace` to uid and gid 0 of this namespace, which is the runner's
136-/// own id on the host. Symlinks are not followed. Entries already owned by 0:0 are left alone.
137-/// Failures are warnings only, because the job has already run.
138 fn reown_workspace(workspace: &Path) {107 fn reown_workspace(workspace: &Path) {
139 let mut stack = vec![workspace.to_owned()];108 let mut stack = vec![workspace.to_owned()];
140 while let Some(path) = stack.pop() {109 while let Some(path) = stack.pop() {
@@ -190,18 +159,11 @@ fn validate_request(req: &SandboxRequest) -> Result<(), SandboxError> {
190 Ok(())159 Ok(())
191 }160 }
192 161
193-/// The signal state the wait loop reads. See [`install_signal_handlers`].
194 struct Signals {162 struct Signals {
195- /// The read end of the self-pipe. SIGTERM, SIGINT and SIGCHLD each write one byte to it, so it
196- /// becomes readable. The byte does not say which signal it was.
197 wake: UnixStream,163 wake: UnixStream,
198- /// Set by SIGTERM and SIGINT.
199 terminate: Arc<AtomicBool>,164 terminate: Arc<AtomicBool>,
200 }165 }
201 166
202-/// Routes SIGTERM, SIGINT and SIGCHLD to a self-pipe, so the wait loop can block in `poll`. SIGTERM
203-/// and SIGINT also set a flag, since the pipe byte doesn't say which signal it was. The handlers
204-/// are installed by `signal-hook`, which does the low-level work, so this file needs none.
205 fn install_signal_handlers() -> Result<Signals, SandboxError> {167 fn install_signal_handlers() -> Result<Signals, SandboxError> {
206 let setup = |e: io::Error| SandboxError::Setup(format!("cannot install signal handler: {e}"));168 let setup = |e: io::Error| SandboxError::Setup(format!("cannot install signal handler: {e}"));
207 let (wake, write_end) =169 let (wake, write_end) =
@@ -247,7 +209,6 @@ fn prepare_dirs(layout: &Layout) -> Result<(), SandboxError> {
247 Ok(())209 Ok(())
248 }210 }
249 211
250-/// The files bind mounted at `/etc/hosts` and `/etc/hostname`.
251 fn write_etc_files(layout: &Layout) -> Result<(), SandboxError> {212 fn write_etc_files(layout: &Layout) -> Result<(), SandboxError> {
252 let hosts = layout.etc.join("hosts");213 let hosts = layout.etc.join("hosts");
253 fs::write(&hosts, HOSTS).map_err(SandboxError::io("cannot write hosts"))?;214 fs::write(&hosts, HOSTS).map_err(SandboxError::io("cannot write hosts"))?;
@@ -264,8 +225,6 @@ fn write_etc_files(layout: &Layout) -> Result<(), SandboxError> {
264 Ok(())225 Ok(())
265 }226 }
266 227
267-/// Mounts the overlay at `merged` and returns it as the rootfs. If the overlay fails, the image
268-/// rootfs is copied instead, and a warning is printed.
269 fn mount_rootfs(req: &SandboxRequest, layout: &Layout) -> Result<PathBuf, SandboxError> {228 fn mount_rootfs(req: &SandboxRequest, layout: &Layout) -> Result<PathBuf, SandboxError> {
270 match mount_overlay(&req.rootfs, layout) {229 match mount_overlay(&req.rootfs, layout) {
271 Ok(()) => Ok(layout.merged.clone()),230 Ok(()) => Ok(layout.merged.clone()),
@@ -304,7 +263,6 @@ fn mount_overlay(lower: &Path, layout: &Layout) -> Result<(), SandboxError> {
304 .map_err(|e| SandboxError::Setup(e.to_string()))263 .map_err(|e| SandboxError::Setup(e.to_string()))
305 }264 }
306 265
307-/// A full copy of the rootfs, reflinked where the filesystem supports it.
308 fn copy_rootfs(src: &Path, dst: &Path) -> Result<(), SandboxError> {266 fn copy_rootfs(src: &Path, dst: &Path) -> Result<(), SandboxError> {
309 let cp = ["/usr/bin/cp", "/bin/cp"]267 let cp = ["/usr/bin/cp", "/bin/cp"]
310 .into_iter()268 .into_iter()
@@ -324,13 +282,6 @@ fn copy_rootfs(src: &Path, dst: &Path) -> Result<(), SandboxError> {
324 }282 }
325 }283 }
326 284
327-/// Runs the job with `[limits]` applied through its cgroup. If the container can't be built that
328-/// way, it is rebuilt in the same cgroup without the limit values, and a warning goes to the job
329-/// log.
330-///
331-/// libcontainer 0.7 cannot run a container in a user namespace without a cgroup manager, and it
332-/// only avoids systemd when the cgroup path is absolute. So "run without cgroups" is not
333-/// available. If the job cgroup can't be created at all, the job fails with exit 125.
334 fn run_job(285 fn run_job(
335 req: &SandboxRequest,286 req: &SandboxRequest,
336 layout: &Layout,287 layout: &Layout,
@@ -353,18 +304,6 @@ fn run_job(
353 }304 }
354 }305 }
355 306
356-/// The job's cgroup path, absolute and relative to the cgroup2 mount.
357-///
358-/// It must not be the runner's own cgroup. libcontainer kills every process in the job cgroup on
359-/// delete, so that would kill the runner. A cgroup that holds processes also can't enable
360-/// controllers for its children. The job cgroup goes in the parent slice instead, when the parent
361-/// is a plain domain cgroup. The runner's user owns both, because systemd delegates the user
362-/// slice.
363-///
364-/// The name is `forge-job-<job id>-<helper pid>`, so the runner can compute it after it has
365-/// spawned the helper. It uses the runner's own cgroup, which is also the helper's, to find the
366-/// parent slice. The path is relative to the cgroup2 mount, so the directory is
367-/// `/sys/fs/cgroup` joined with it.
368 pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, SandboxError> {307 pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, SandboxError> {
369 let base = job_cgroup_base()?;308 let base = job_cgroup_base()?;
370 let base = if box_ready(&base) {309 let base = if box_ready(&base) {
@@ -375,11 +314,8 @@ pub fn job_cgroup_path(job_id: &str, helper_pid: u32) -> Result<PathBuf, Sandbox
375 Ok(base.join(format!("forge-job-{job_id}-{helper_pid}")))314 Ok(base.join(format!("forge-job-{job_id}-{helper_pid}")))
376 }315 }
377 316
378-/// The name of the runner's box cgroup, the parent of every job cgroup when memory control is on.
379 pub const BOX_NAME: &str = "forge-jobs";317 pub const BOX_NAME: &str = "forge-jobs";
380 318
381-/// The cgroup that holds the job cgroups, or the box under it: the runner's parent cgroup when it
382-/// is a plain domain cgroup, else the runner's own. Absolute, relative to the cgroup2 mount.
383 pub fn job_cgroup_base() -> Result<PathBuf, SandboxError> {319 pub fn job_cgroup_base() -> Result<PathBuf, SandboxError> {
384 let text = fs::read_to_string("/proc/self/cgroup")320 let text = fs::read_to_string("/proc/self/cgroup")
385 .map_err(SandboxError::io("cannot read /proc/self/cgroup"))?;321 .map_err(SandboxError::io("cannot read /proc/self/cgroup"))?;
@@ -394,7 +330,6 @@ pub fn job_cgroup_base() -> Result<PathBuf, SandboxError> {
394 })330 })
395 }331 }
396 332
397-/// Whether the box exists under `base` with the memory controller enabled for its children.
398 fn box_ready(base: &Path) -> bool {333 fn box_ready(base: &Path) -> bool {
399 let dir = Path::new("/sys/fs/cgroup")334 let dir = Path::new("/sys/fs/cgroup")
400 .join(base.strip_prefix("/").unwrap_or(base))335 .join(base.strip_prefix("/").unwrap_or(base))
@@ -403,8 +338,6 @@ fn box_ready(base: &Path) -> bool {
403 .is_ok_and(|t| t.split_whitespace().any(|c| c == "memory"))338 .is_ok_and(|t| t.split_whitespace().any(|c| c == "memory"))
404 }339 }
405 340
406-/// Whether `cgroup` (absolute, inside the cgroup2 mount) is a normal domain cgroup. A threaded
407-/// one can't hold domain children.
408 fn is_plain_domain(cgroup: &Path) -> bool {341 fn is_plain_domain(cgroup: &Path) -> bool {
409 let file = Path::new("/sys/fs/cgroup")342 let file = Path::new("/sys/fs/cgroup")
410 .join(cgroup.strip_prefix("/").unwrap_or(cgroup))343 .join(cgroup.strip_prefix("/").unwrap_or(cgroup))
@@ -418,15 +351,12 @@ fn set_cgroup_path(spec: &mut Spec, cgroup: &Path) {
418 }351 }
419 }352 }
420 353
421-/// Removes the resource values. The cgroup path stays, so libcontainer still uses the fs driver.
422 fn strip_limits(spec: &mut Spec) {354 fn strip_limits(spec: &mut Spec) {
423 if let Some(linux) = spec.linux_mut() {355 if let Some(linux) = spec.linux_mut() {
424 linux.set_resources(None);356 linux.set_resources(None);
425 }357 }
426 }358 }
427 359
428-/// Writes the bundle, builds, starts, and waits. Build and start errors are returned as
429-/// `Setup("container: …")` so the caller can tell them apart from setup errors.
430 fn launch_and_wait(360 fn launch_and_wait(
431 layout: &Layout,361 layout: &Layout,
432 id: &str,362 id: &str,
@@ -463,8 +393,6 @@ fn launch_and_wait(
463 wait_for_init(&mut container, pid, cgroup.as_deref(), signals)393 wait_for_init(&mut container, pid, cgroup.as_deref(), signals)
464 }394 }
465 395
466-/// Writes `bundle/config.json` (0600). It holds the job env and secrets, so it is removed right
467-/// after `build()`.
468 fn write_bundle(layout: &Layout, spec: &Spec) -> Result<(), SandboxError> {396 fn write_bundle(layout: &Layout, spec: &Spec) -> Result<(), SandboxError> {
469 let json = serde_json::to_vec(spec)397 let json = serde_json::to_vec(spec)
470 .map_err(|e| SandboxError::Setup(format!("cannot serialize spec: {e}")))?;398 .map_err(|e| SandboxError::Setup(format!("cannot serialize spec: {e}")))?;
@@ -485,8 +413,6 @@ fn write_bundle(layout: &Layout, spec: &Spec) -> Result<(), SandboxError> {
485 .map_err(SandboxError::io("cannot write bundle config"))413 .map_err(SandboxError::io("cannot write bundle config"))
486 }414 }
487 415
488-/// Creates the container. Its stdin is `/dev/null`. Its stdout and stderr are dups of the
489-/// helper's, so the runner receives them.
490 fn build_container(layout: &Layout, id: &str) -> Result<Container, String> {416 fn build_container(layout: &Layout, id: &str) -> Result<Container, String> {
491 let io_err = |e: io::Error| e.to_string();417 let io_err = |e: io::Error| e.to_string();
492 let devnull = fs::File::open("/dev/null").map_err(io_err)?;418 let devnull = fs::File::open("/dev/null").map_err(io_err)?;
@@ -509,7 +435,6 @@ fn build_container(layout: &Layout, id: &str) -> Result<Container, String> {
509 .map_err(|e| e.to_string())435 .map_err(|e| e.to_string())
510 }436 }
511 437
512-/// Starts the container and returns the init pid. The init is a child of this process.
513 fn start_container(container: &mut Container) -> Result<Pid, SandboxError> {438 fn start_container(container: &mut Container) -> Result<Pid, SandboxError> {
514 container439 container
515 .start()440 .start()
@@ -520,8 +445,6 @@ fn start_container(container: &mut Container) -> Result<Pid, SandboxError> {
520 .ok_or_else(|| SandboxError::Setup("container: no init pid".into()))445 .ok_or_else(|| SandboxError::Setup("container: no init pid".into()))
521 }446 }
522 447
523-/// SIGKILL, as libcontainer's own signal type. Its `Signal` is not nix's, so it is built from
524-/// the number.
525 const SIGKILL_NUMBER: i32 = 9;448 const SIGKILL_NUMBER: i32 = 9;
526 449
527 fn kill_container(container: &mut Container) -> Result<(), String> {450 fn kill_container(container: &mut Container) -> Result<(), String> {
@@ -530,8 +453,6 @@ fn kill_container(container: &mut Container) -> Result<(), String> {
530 container.kill(sigkill, true).map_err(|e| e.to_string())453 container.kill(sigkill, true).map_err(|e| e.to_string())
531 }454 }
532 455
533-/// Waits for the init process. On SIGTERM or SIGINT the container is killed. The child is then
534-/// reaped, and `delete` removes the container's state. Returns the job's exit code.
535 fn wait_for_init(456 fn wait_for_init(
536 container: &mut Container,457 container: &mut Container,
537 pid: Pid,458 pid: Pid,
@@ -575,9 +496,6 @@ fn wait_for_init(
575 }496 }
576 }497 }
577 498
578-/// Blocks until the self-pipe is readable, then empties it. The pipe is only written by signal
579-/// handlers, so this wakes on any of SIGTERM, SIGINT or SIGCHLD. Returns an error only if `poll`
580-/// itself fails.
581 fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> {499 fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> {
582 let mut fds = [PollFd::new(wake.as_fd(), PollFlags::POLLIN)];500 let mut fds = [PollFd::new(wake.as_fd(), PollFlags::POLLIN)];
583 match poll(&mut fds, PollTimeout::NONE) {501 match poll(&mut fds, PollTimeout::NONE) {
@@ -595,8 +513,6 @@ fn wait_for_signal(wake: &UnixStream) -> Result<(), Errno> {
595 }513 }
596 }514 }
597 515
598-/// Prints the job cgroup's OOM counters for the runner when something was OOM-killed. It runs
599-/// after the init exited and before the cgroup is deleted, the only time the file still exists.
600 fn report_oom(cgroup: Option<&Path>) {516 fn report_oom(cgroup: Option<&Path>) {
601 let Some(cgroup) = cgroup else {517 let Some(cgroup) = cgroup else {
602 return;518 return;
@@ -617,10 +533,6 @@ fn delete_container(container: &mut Container) {
617 }533 }
618 }534 }
619 535
620-/// Removes the whole job dir: state and bundle (which hold the env), and the overlay upper dir
621-/// (which may hold files the job wrote). The container is gone by now. The overlay is still
622-/// mounted in this process's mount namespace, so detach it first. The helper is still root in its
623-/// user namespace, so it can remove the overlay work files that the runner's uid could not.
624 fn cleanup(layout: &Layout) {536 fn cleanup(layout: &Layout) {
625 let _ = umount2(layout.merged.as_path(), MntFlags::MNT_DETACH);537 let _ = umount2(layout.merged.as_path(), MntFlags::MNT_DETACH);
626 if let Err(e) = fs::remove_dir_all(&layout.job_dir) {538 if let Err(e) = fs::remove_dir_all(&layout.job_dir) {
crates/forge-runner/src/sandbox/idmap.rsmodified+0 -78

Diff too large; view file

@@ -1,18 +1,3 @@
1-//! User and group id mapping for the sandbox's user namespaces.
2-//!
3-//! Two modes:
4-//! - **single**: the runner's uid and gid map to container 0 and nothing else. Jobs can't
5-//! `chown` to other ids.
6-//! - **subuid**: container 0 maps to the runner's uid, and container `1..=n` map to the range
7-//! granted in `/etc/subuid` and `/etc/subgid`. Writing a map with more than one line needs the
8-//! setuid helpers `newuidmap` and `newgidmap` from shadow-utils, so that is what the helper
9-//! runs.
10-//!
11-//! The namespace entry functions ([`enter_mapped_userns`]) must run in a single-threaded process,
12-//! because `unshare(CLONE_NEWUSER)` fails in a multi-threaded one. The sandbox helpers are
13-//! single-threaded. Subuid mode never forks: it starts a `__sandbox-map` helper of this same
14-//! binary with `std::process::Command`, and that helper writes the maps.
15-
16 use std::ffi::OsString;1 use std::ffi::OsString;
crates/forge-runner/src/sandbox/mod.rsmodified+0 -24

Diff too large; view file

crates/forge-runner/src/sandbox/net.rsmodified+0 -37

Diff too large; view file

crates/forge-runner/src/sandbox/seccomp.rsmodified+0 -18

Diff too large; view file

crates/forge-runner/src/sandbox/spec.rsmodified+0 -26

Diff too large; view file

crates/forge-runner/src/selflog.rsmodified+0 -28

Diff too large; view file

crates/forge-runner/src/update.rsmodified+0 -37

Diff too large; view file

crates/forge-runner/src/workspace.rsmodified+0 -18

Diff too large; view file

crates/forge-runner/tests/integration/builtin.rsmodified+0 -22

Diff too large; view file

crates/forge-runner/tests/integration/common/mod.rsmodified+0 -3

Diff too large; view file

crates/forge-runner/tests/integration/flow.rsmodified+0 -26

Diff too large; view file

crates/forge-runner/tests/integration/idmap.rsmodified+0 -4

Diff too large; view file

crates/forge-runner/tests/integration/main.rsmodified+0 -2

Diff too large; view file

crates/forge-runner/tests/integration/unpack_subuid.rsmodified+0 -9

Diff too large; view file

crates/forge-ssh/src/backend.rsmodified+0 -8

Diff too large; view file

crates/forge-ssh/src/error.rsmodified+0 -2

Diff too large; view file

crates/forge-ssh/src/lib.rsmodified+0 -2

Diff too large; view file

crates/forge-ssh/src/parse.rsmodified+0 -34

Diff too large; view file

crates/forge-ssh/tests/ssh_e2e.rsmodified+0 -17

Diff too large; view file

crates/forge-web-account/src/lib.rsmodified+0 -2

Diff too large; view file

crates/forge-web-account/src/pages/account_tools_tests.rsmodified+0 -9

Diff too large; view file

crates/forge-web-account/src/pages/activity.rsmodified+0 -19

Diff too large; view file

crates/forge-web-account/src/pages/admin_backups.rsmodified+0 -26

Diff too large; view file

crates/forge-web-account/src/pages/admin_health.rsmodified+0 -47

Diff too large; view file

crates/forge-web-account/src/pages/admin_live_tests.rsmodified+0 -18

Diff too large; view file

crates/forge-web-account/src/pages/admin_replication.rsmodified+0 -35

Diff too large; view file

crates/forge-web-account/src/pages/admin_user_detail.rsmodified+0 -20

Diff too large; view file

crates/forge-web-account/src/pages/assets.rsmodified+0 -30

Diff too large; view file

crates/forge-web-account/src/pages/audit_log.rsmodified+0 -63

Diff too large; view file

crates/forge-web-account/src/pages/avatars.rsmodified+0 -7

Diff too large; view file

crates/forge-web-account/src/pages/banner.rsmodified+0 -6

Diff too large; view file

crates/forge-web-account/src/pages/explore.rsmodified+0 -21

Diff too large; view file

crates/forge-web-account/src/pages/forgot.rsmodified+0 -22

Diff too large; view file

crates/forge-web-account/src/pages/home.rsmodified+0 -16

Diff too large; view file

crates/forge-web-account/src/pages/import_tests.rsmodified+0 -11

Diff too large; view file

crates/forge-web-account/src/pages/invites.rsmodified+0 -4

Diff too large; view file

crates/forge-web-account/src/pages/login.rsmodified+0 -47

Diff too large; view file

crates/forge-web-account/src/pages/mod.rsmodified+0 -2

Diff too large; view file

crates/forge-web-account/src/pages/needs_you.rsmodified+0 -30

Diff too large; view file

crates/forge-web-account/src/pages/not_found_page.rsmodified+0 -5

Diff too large; view file

crates/forge-web-account/src/pages/org_ctx.rsmodified+0 -33

Diff too large; view file

crates/forge-web-account/src/pages/org_live.rsmodified+0 -26

Diff too large; view file

crates/forge-web-account/src/pages/org_members.rsmodified+0 -14

Diff too large; view file

crates/forge-web-account/src/pages/org_new.rsmodified+0 -8

Diff too large; view file

crates/forge-web-account/src/pages/org_settings.rsmodified+0 -20

Diff too large; view file

crates/forge-web-account/src/pages/org_teams.rsmodified+0 -30

Diff too large; view file

crates/forge-web-account/src/pages/palette.rsmodified+0 -38

Diff too large; view file

crates/forge-web-account/src/pages/passkeys.rsmodified+0 -49

Diff too large; view file

crates/forge-web-account/src/pages/passkeys_tests.rsmodified+0 -24

Diff too large; view file

crates/forge-web-account/src/pages/profile_calendar.rsmodified+0 -11

Diff too large; view file

crates/forge-web-account/src/pages/profile_pins.rsmodified+0 -25

Diff too large; view file

crates/forge-web-account/src/pages/register.rsmodified+0 -39

Diff too large; view file

crates/forge-web-account/src/pages/settings_export.rsmodified+0 -17

Diff too large; view file

crates/forge-web-account/src/pages/settings_gpg.rsmodified+0 -4

Diff too large; view file

crates/forge-web-account/src/pages/settings_gpg_tests.rsmodified+0 -13

Diff too large; view file

crates/forge-web-account/src/pages/settings_keys.rsmodified+0 -21

Diff too large; view file

crates/forge-web-account/src/pages/settings_notifications.rsmodified+0 -20

Diff too large; view file

crates/forge-web-account/src/pages/settings_profile.rsmodified+0 -58

Diff too large; view file

crates/forge-web-account/src/pages/settings_security.rsmodified+0 -78

Diff too large; view file

crates/forge-web-account/src/pages/settings_sessions.rsmodified+0 -6

Diff too large; view file

crates/forge-web-account/src/pages/settings_tokens.rsmodified+0 -9

Diff too large; view file

crates/forge-web-account/src/pages/setup.rsmodified+0 -18

Diff too large; view file

crates/forge-web-account/src/pages/shell_events.rsmodified+0 -15

Diff too large; view file

crates/forge-web-account/src/pages/snippets_live.rsmodified+0 -19

Diff too large; view file

crates/forge-web-account/src/pages/theme_cookie.rsmodified+0 -8

Diff too large; view file

crates/forge-web-account/src/pages/user_prefs.rsmodified+0 -6

Diff too large; view file

crates/forge-web-app/build.rsmodified+0 -29

Diff too large; view file

crates/forge-web-app/src/access.rsmodified+0 -22

Diff too large; view file

crates/forge-web-app/src/admin_client.rsmodified+0 -25

Diff too large; view file

crates/forge-web-app/src/advisories/mod.rsmodified+0 -4

Diff too large; view file

crates/forge-web-app/src/advisories/scan.rsmodified+0 -13

Diff too large; view file

crates/forge-web-app/src/advisories/worker.rsmodified+0 -29

Diff too large; view file

crates/forge-web-app/src/alerts.rsmodified+0 -51

Diff too large; view file

crates/forge-web-app/src/api/gitea.rsmodified+0 -46

Diff too large; view file

crates/forge-web-app/src/api/mod.rsmodified+0 -33

Diff too large; view file

crates/forge-web-app/src/api/packages.rsmodified+0 -28

Diff too large; view file

crates/forge-web-app/src/api/releases.rsmodified+0 -32

Diff too large; view file

crates/forge-web-app/src/api/statuses.rsmodified+0 -14

Diff too large; view file

crates/forge-web-app/src/audit.rsmodified+0 -9

Diff too large; view file

crates/forge-web-app/src/automerge.rsmodified+0 -19

Diff too large; view file

crates/forge-web-app/src/backup/create.rsmodified+0 -16

Diff too large; view file

crates/forge-web-app/src/backup/fsck.rsmodified+0 -11

Diff too large; view file

crates/forge-web-app/src/backup/healthcheck.rsmodified+0 -11

Diff too large; view file

crates/forge-web-app/src/backup/mod.rsmodified+0 -32

Diff too large; view file

crates/forge-web-app/src/backup/restore.rsmodified+0 -23

Diff too large; view file

crates/forge-web-app/src/backup/retention.rsmodified+0 -13

Diff too large; view file

crates/forge-web-app/src/backup/scheduler.rsmodified+0 -50

Diff too large; view file

crates/forge-web-app/src/backup/tests.rsmodified+0 -18

Diff too large; view file

crates/forge-web-app/src/backup/verify.rsmodified+0 -17

Diff too large; view file

crates/forge-web-app/src/ci/api.rsmodified+0 -107

Diff too large; view file

crates/forge-web-app/src/ci/api_tests.rsmodified+0 -94

Diff too large; view file

crates/forge-web-app/src/ci/live.rsmodified+0 -45

Diff too large; view file

crates/forge-web-app/src/ci/metrics_chart.rsmodified+0 -37

Diff too large; view file

crates/forge-web-app/src/ci/mod.rsmodified+0 -24

Diff too large; view file

crates/forge-web-app/src/ci/reaper.rsmodified+0 -23

Diff too large; view file

crates/forge-web-app/src/ci/runner_log.rsmodified+0 -35

Diff too large; view file

crates/forge-web-app/src/ci/runner_metrics.rsmodified+0 -13

Diff too large; view file

crates/forge-web-app/src/ci/schedule.rsmodified+1 -79

Diff too large; view file

crates/forge-web-app/src/ci/scheduled.rsmodified+0 -28

Diff too large; view file

crates/forge-web-app/src/client_ip.rsmodified+0 -15

Diff too large; view file

crates/forge-web-app/src/exporter.rsmodified+0 -28

Diff too large; view file

crates/forge-web-app/src/exporter/tests.rsmodified+0 -4

Diff too large; view file

crates/forge-web-app/src/git_auth.rsmodified+0 -17

Diff too large; view file

crates/forge-web-app/src/git_http.rsmodified+0 -33

Diff too large; view file

crates/forge-web-app/src/hook_cmd.rsmodified+0 -13

Diff too large; view file

crates/forge-web-app/src/importer/mod.rsmodified+0 -50

Diff too large; view file

crates/forge-web-app/src/importer/remote.rsmodified+0 -10

Diff too large; view file

crates/forge-web-app/src/internal.rsmodified+0 -60

Diff too large; view file

crates/forge-web-app/src/layers.rsmodified+12 -71

Diff too large; view file

crates/forge-web-app/src/lfs/gc.rsmodified+0 -22

Diff too large; view file

crates/forge-web-app/src/lfs/mod.rsmodified+0 -14

Diff too large; view file

crates/forge-web-app/src/lfs/route_tests.rsmodified+0 -6

Diff too large; view file

crates/forge-web-app/src/lfs/routes.rsmodified+0 -33

Diff too large; view file

crates/forge-web-app/src/lfs_pointer.rsmodified+0 -16

Diff too large; view file

crates/forge-web-app/src/lib.rsmodified+0 -2

Diff too large; view file

crates/forge-web-app/src/live.rsmodified+0 -157

Diff too large; view file