OXYGENHUB

Coverage / crates/hub/src/web/runner_updates.rs 93.0%

387 of 416 lines run, 65 of 152 functions · run #544 on main · run missed

1
//! Admin → Runners → Updates (oxygenhub#322): where runner builds come
2
//! from, and who takes them: the site's, each owner's, each test group's
3
//! and each runner's settings, the nearest winning; test groups of chosen
4
//! runners or a percentage of them.
5
6
use super::settings::csrf;
7
use super::{filters, Error, Page, Shell};
8
use crate::auth::Viewer;
9
use crate::db::runner_updates::{self as rdb, Group, Policy};
10
use crate::db::{accounts, runners};
11
use crate::runner_updates::{self as ru, Levels};
12
use crate::Shared;
13
use askama::Template;
14
use axum::extract::{Form, Path, State};
15
use flow_core::api::UpdatePolicy;
16
use serde::Deserialize;
17
1829×
fn require_admin(viewer: &Viewer, shell: &Shell) -> Result<accounts::Account, Error> {
1929×
    match viewer.account() {
2028×
        Some(a) if a.is_admin => Ok(a.clone()),
211×
        _ => Err(Error::not_found(shell.clone())),
22
    }
2329×
}
24
25
/// One level's settings as its form shows them: `inherit`, `on` or `off`
26
/// for the switches, blank for an inherited channel or window.
27
pub struct PolicyView {
28
    pub scope: String,
29
    pub key: String,
30
    pub label: String,
31
    pub updates: &'static str,
32
    pub channel: String,
33
    pub window: String,
34
    pub dry_run: &'static str,
35
}
36
37
impl PolicyView {
38209×
    fn of(p: &Policy, label: String) -> PolicyView {
39418×
        let tri = |b: Option<bool>| match b {
4075×
            Some(true) => "on",
4119×
            Some(false) => "off",
42324×
            None => "inherit",
43418×
        };
44
        PolicyView {
45209×
            scope: p.scope.clone(),
46209×
            key: p.key.clone(),
47209×
            label,
48209×
            updates: tri(p.updates),
49209×
            channel: p.channel.clone().unwrap_or_default(),
50209×
            window: match (p.window_from, p.window_to) {
5112×
                (Some(a), Some(b)) => format!("{a:02}-{b:02}"),
52197×
                _ => String::new(),
53
            },
54209×
            dry_run: tri(p.dry_run),
55
        }
56209×
    }
57
58
    /// The settings in words, for a table.
5938×
    pub fn summary(&self) -> String {
6038×
        let mut s = vec![];
6138×
        if self.updates != "inherit" {
6229×
            s.push(format!("updates {}", self.updates));
6329×
        }
6438×
        if !self.channel.is_empty() {
653×
            s.push(format!("channel {}", self.channel));
6635×
        }
6738×
        if !self.window.is_empty() {
681×
            s.push(format!("window {} UTC", self.window));
6937×
        }
7038×
        if self.dry_run != "inherit" {
7114×
            s.push(format!("dry run {}", self.dry_run));
7224×
        }
7338×
        if s.is_empty() {
748×
            "inherits everything".into()
75
        } else {
7630×
            s.join(", ")
77
        }
7838×
    }
79
}
80
81
pub struct GroupView {
82
    pub g: Group,
83
    /// Whom it can hold, in words.
84
    pub reach: String,
85
    /// Its members now, by name.
86
    pub members: Vec<String>,
87
    pub chosen: Vec<i64>,
88
    pub policy: PolicyView,
89
}
90
91
pub struct RunnerView {
92
    pub r: runners::Runner,
93
    pub groups: Vec<String>,
94
    pub effective: UpdatePolicy,
95
    /// What the hub would offer it now.
96
    pub offer: String,
97
    pub policy: PolicyView,
98
}
99
100
impl RunnerView {
101
    /// Its effective settings, each with where it came from.
10273×
    pub fn effective_words(&self) -> String {
10373×
        let e = &self.effective;
10473×
        let mut s = vec![format!("updates {} ({})", if e.updates { "on" } else { "off" }, e.from[0])];
10573×
        if e.updates {
10655×
            s.push(format!("channel {} ({})", e.channel, e.from[1]));
10755×
            if let Some((a, b)) = e.window {
10810×
                s.push(format!("window {a:02}–{b:02} UTC ({})", e.from[2]));
10945×
            }
11055×
            if e.dry_run {
11123×
                s.push(format!("dry run ({})", e.from[3]));
11232×
            }
11318×
        }
11473×
        s.join(" · ")
11573×
    }
116
}
117
118
#[derive(Template)]
119
#[template(path = "admin_runner_updates.html")]
120
pub struct UpdatesPage {
121
    shell: Shell,
122
    repo: String,
123
    site: PolicyView,
124
    owners: Vec<PolicyView>,
125
    groups: Vec<GroupView>,
126
    runners: Vec<RunnerView>,
127
    /// Builds held back after rolling back on a runner (#326).
128
    holds: Vec<rdb::Hold>,
129
    /// Proving a version in a wave (oxygenflow#84).
130
    soak_jobs: i64,
131
    soak_hours: i64,
132
    notice: Option<String>,
133
    error: Option<String>,
134
}
135
136
/// Who changes runner updates: the site's administrators anything; an
137
/// organisation's owners their organisation's setting, its test groups and
138
/// its runners (Andy: an organisation tries a build on some of its runners
139
/// before the rest).
140
#[derive(Clone, Debug, PartialEq, Eq)]
141
pub enum Reach {
142
    Site,
143
    Org(String),
144
}
145
146
impl Reach {
14794×
    fn holds_runner(&self, r: &runners::Runner) -> bool {
14894×
        match self {
14959×
            Reach::Site => true,
15035×
            Reach::Org(o) => r.scope_owner == *o,
151
        }
15294×
    }
153
15438×
    fn holds_group(&self, g: &Group) -> bool {
15538×
        match self {
15629×
            Reach::Site => true,
1579×
            Reach::Org(o) => g.owner == *o,
158
        }
15938×
    }
160
}
161
162
/// What a page shows of runner updates, within `reach`.
163
pub struct UpdateViews {
164
    pub site: PolicyView,
165
    pub owners: Vec<PolicyView>,
166
    pub groups: Vec<GroupView>,
167
    pub runners: Vec<RunnerView>,
168
}
169
17061×
pub async fn views(app: &Shared, reach: &Reach) -> sqlx::Result<UpdateViews> {
17161×
    let levels = Levels::load(&app.db).await?;
17261×
    let all = runners::list(&app.db).await?;
173199×
    let policy = |scope: &str, key: &str| {
174199×
        levels.policies.get(&(scope.to_string(), key.to_string())).cloned().unwrap_or(Policy {
175199×
            scope: scope.into(),
176199×
            key: key.into(),
177199×
            ..Policy::default()
178199×
        })
179199×
    };
18061×
    let mut owners: Vec<PolicyView> = match reach {
181
        Reach::Site => {
18250×
            levels.policies.values().filter(|p| p.scope == "owner").map(|p| PolicyView::of(p, format!("owner {}", p.key))).collect()
183
        }
18431×
        Reach::Org(o) => vec![PolicyView::of(&policy("owner", o), format!("owner {o}"))],
185
    };
18661×
    owners.sort_by(|a, b| a.key.cmp(&b.key));
18761×
    let groups = levels
18861×
        .groups
18961×
        .iter()
19061×
        .filter(|g| reach.holds_group(g))
19161×
        .map(|g| GroupView {
19230×
            g: g.clone(),
19330×
            reach: if g.owner.is_empty() { "the site's runners".into() } else { format!("{}'s runners", g.owner) },
19465×
            members: all.iter().filter(|r| levels.member(g, r)).map(|r| r.name.clone()).collect(),
19537×
            chosen: levels.chosen.iter().filter(|(gid, _)| *gid == g.id).map(|(_, r)| *r).collect(),
19630×
            policy: PolicyView::of(&policy("group", &g.id.to_string()), format!("group {}", g.name)),
19730×
        })
19861×
        .collect();
19961×
    let hour = time::OffsetDateTime::now_utc().hour();
20061×
    let mut out = vec![];
20190×
    for r in all.into_iter().filter(|r| reach.holds_runner(r)) {
20277×
        let effective = levels.resolve(&r);
20377×
        let (_, offer) = ru::offer(&app.db, &levels, &r, &effective, hour, crate::db::now_ms(), false).await?;
20477×
        out.push(RunnerView {
20577×
            groups: levels.groups_of(&r).iter().map(|g| g.name.clone()).collect(),
20677×
            policy: PolicyView::of(&policy("runner", &r.id.to_string()), format!("runner {}", r.name)),
20777×
            effective,
20877×
            offer,
20977×
            r,
210
        });
211
    }
21261×
    Ok(UpdateViews { site: PolicyView::of(&policy("site", ""), "the site".into()), owners, groups, runners: out })
21361×
}
214
21528×
async fn page(app: &Shared, shell: Shell, notice: Option<String>, error: Option<String>) -> Result<Page<UpdatesPage>, Error> {
21628×
    let e = |e| Error::from_db(shell.clone(), e);
21728×
    let repo = accounts::setting(&app.db, ru::SETTING_REPO).await.map_err(e)?.unwrap_or_default();
21828×
    let v = views(app, &Reach::Site).await.map_err(e)?;
21928×
    let holds = rdb::holds(&app.db).await.map_err(e)?;
22056×
    let number = |v: Option<String>, d: i64| v.and_then(|s| s.trim().parse::<i64>().ok()).filter(|n| *n > 0).unwrap_or(d);
22128×
    let soak_jobs = number(accounts::setting(&app.db, ru::SETTING_SOAK_JOBS).await.map_err(e)?, ru::SOAK_JOBS);
22228×
    let soak_hours = number(accounts::setting(&app.db, ru::SETTING_SOAK_HOURS).await.map_err(e)?, ru::SOAK_HOURS);
22328×
    Ok(Page(UpdatesPage {
22428×
        shell,
22528×
        repo,
22628×
        site: v.site,
22728×
        owners: v.owners,
22828×
        groups: v.groups,
22928×
        runners: v.runners,
23028×
        holds,
23128×
        soak_jobs,
23228×
        soak_hours,
23328×
        notice,
23428×
        error,
23528×
    }))
23628×
}
237
238
/// What a change did, to say on the page: `Ok` a notice, `Err` what was wrong.
239
pub type Outcome = Result<String, String>;
240
241
/// [`page`] saying what `outcome` did.
24215×
async fn page_after(app: &Shared, shell: Shell, outcome: Outcome) -> Result<Page<UpdatesPage>, Error> {
24315×
    match outcome {
24411×
        Ok(n) => page(app, shell, Some(n), None).await,
2454×
        Err(why) => page(app, shell, None, Some(why)).await,
246
    }
24715×
}
248
2498×
pub async fn show(State(app): State<Shared>, viewer: Viewer) -> Result<Page<UpdatesPage>, Error> {
2508×
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
2518×
    require_admin(&viewer, &shell)?;
2527×
    page(&app, shell, None, None).await
2538×
}
254
255
#[derive(Deserialize)]
256
pub struct SourceForm {
257
    #[serde(rename = "_csrf")]
258
    csrf_token: String,
259
    repo: String,
260
    #[serde(default)]
261
    soak_jobs: String,
262
    #[serde(default)]
263
    soak_hours: String,
264
}
265
266
/// `POST /admin/runners/updates/source`: the repository whose releases carry runner builds.
2674×
pub async fn save_source(State(app): State<Shared>, viewer: Viewer, Form(f): Form<SourceForm>) -> Result<Page<UpdatesPage>, Error> {
2684×
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
2694×
    let me = require_admin(&viewer, &shell)?;
2704×
    csrf(&viewer, &f.csrf_token, &shell)?;
2714×
    let repo = f.repo.trim().trim_matches('/').to_string();
2724×
    if !repo.is_empty() {
2734×
        let found = match repo.split_once('/') {
2744×
            Some((o, n)) => crate::db::repos::get(&app.db, o, n).await.map_err(|e| Error::from_db(shell.clone(), e))?,
2750×
            None => None,
276
        };
2774×
        if found.is_none() {
2781×
            return page(&app, shell, None, Some(format!("There is no repository {repo:?} here; give it as owner/name."))).await;
2793×
        }
2800×
    }
281
    // Waves (oxygenflow#84): blank keeps the default.
2825×
    for (key, value, max, what) in [
2833×
        (ru::SETTING_SOAK_JOBS, &f.soak_jobs, 1000, "jobs each runner of a wave finishes"),
2843×
        (ru::SETTING_SOAK_HOURS, &f.soak_hours, 720, "hours a wave soaks"),
2853×
    ] {
2865×
        let v = value.trim();
2875×
        if !v.is_empty() && !v.parse::<i64>().is_ok_and(|n| (1..=max).contains(&n)) {
2881×
            return page(&app, shell, None, Some(format!("The {what} is a whole number from 1 to {max}."))).await;
2894×
        }
2904×
        accounts::set_setting(&app.db, key, v).await.map_err(|e| Error::from_db(shell.clone(), e))?;
291
    }
2922×
    accounts::set_setting(&app.db, ru::SETTING_REPO, &repo).await.map_err(|e| Error::from_db(shell.clone(), e))?;
2932×
    accounts::audit(&app.db, Some(&me), "runner.updates.source", &repo, "runner builds come from its releases").await.ok();
2942×
    let n = if repo.is_empty() {
2950×
        "Saved: no repository, so no runner is offered a build.".into()
296
    } else {
2972×
        format!("Saved: runner builds come from {repo}'s releases.")
298
    };
2992×
    page(&app, shell, Some(n), None).await
3004×
}
301
302
#[derive(Deserialize)]
303
pub struct PolicyForm {
304
    #[serde(rename = "_csrf")]
305
    pub(crate) csrf_token: String,
306
    scope: String,
307
    #[serde(default)]
308
    key: String,
309
    #[serde(default)]
310
    updates: String,
311
    #[serde(default)]
312
    channel: String,
313
    #[serde(default)]
314
    window: String,
315
    #[serde(default)]
316
    dry_run: String,
317
}
318
319
impl PolicyForm {
320
    /// The form an API setting stands for.
3212×
    pub fn of(u: &hub_api::UpdateSetting) -> PolicyForm {
3224×
        let tri = |b: Option<bool>| match b {
3232×
            Some(true) => "on",
3240×
            Some(false) => "off",
3252×
            None => "inherit",
3264×
        };
3272×
        PolicyForm {
3282×
            csrf_token: String::new(),
3292×
            scope: u.scope.clone(),
3302×
            key: u.key.clone(),
3312×
            updates: tri(u.updates).into(),
3322×
            channel: u.channel.clone().unwrap_or_default(),
3332×
            window: u.window.clone().unwrap_or_default(),
3342×
            dry_run: tri(u.dry_run).into(),
3352×
        }
3362×
    }
337
}
338
339
/// Set one level's settings, within `reach`.
34016×
pub async fn apply_policy(app: &Shared, me: &accounts::Account, reach: &Reach, f: &PolicyForm) -> sqlx::Result<Outcome> {
34116×
    let key = f.key.trim().to_string();
34216×
    let label = match (f.scope.as_str(), reach) {
34316×
        ("site", Reach::Site) if key.is_empty() => "the site".to_string(),
3449×
        ("owner", Reach::Org(o)) if key != *o => return Ok(Err("An organisation sets its own runners' updates only.".into())),
345
        ("owner", _) => {
3461×
            let known = accounts::account_by_name(&app.db, &key).await?.is_some() || accounts::org_by_name(&app.db, &key).await?.is_some();
3471×
            if !known {
3480×
                return Ok(Err(format!("There is no account or organisation {key:?}.")));
3491×
            }
3501×
            format!("owner {key}")
351
        }
3527×
        ("group", _) => match key.parse().ok() {
3533×
            Some(id) => match rdb::group(&app.db, id).await?.filter(|g| reach.holds_group(g)) {
3543×
                Some(g) => format!("group {}", g.name),
3550×
                None => return Ok(Err("That test group is gone.".into())),
356
            },
3570×
            None => return Ok(Err("That test group is gone.".into())),
358
        },
3594×
        ("runner", _) => match key.parse().ok() {
3604×
            Some(id) => match runners::get(&app.db, id).await?.filter(|r| reach.holds_runner(r)) {
3613×
                Some(r) => format!("runner {}", r.name),
3621×
                None => return Ok(Err("That runner is gone.".into())),
363
            },
3640×
            None => return Ok(Err("That runner is gone.".into())),
365
        },
3661×
        _ => return Ok(Err("Choose the site, an owner, a test group or a runner.".into())),
367
    };
36820×
    let tri = |v: &str| match v {
36920×
        "on" => Some(true),
37011×
        "off" => Some(false),
3719×
        _ => None,
37220×
    };
37313×
    let channel = f.channel.trim().to_string();
37413×
    if !channel.is_empty() && !ru::valid_channel(&channel) {
3752×
        return Ok(Err(format!("A channel is stable, canary or a version such as 0.3.4, not {channel:?}.")));
37611×
    }
37711×
    let window = match ru::parse_window(&f.window) {
37810×
        Ok(w) => w,
3791×
        Err(why) => return Ok(Err(format!("{why}."))),
380
    };
38110×
    let p = Policy {
38210×
        scope: f.scope.clone(),
38310×
        key,
38410×
        updates: tri(&f.updates),
38510×
        channel: Some(channel).filter(|c| !c.is_empty()),
38610×
        window_from: window.map(|w| w.0 as i64),
38710×
        window_to: window.map(|w| w.1 as i64),
38810×
        dry_run: tri(&f.dry_run),
389
    };
39010×
    rdb::set_policy(&app.db, &p).await?;
39110×
    let words = PolicyView::of(&p, label.clone()).summary();
39210×
    accounts::audit(&app.db, Some(me), "runner.updates.policy", &label, &words).await.ok();
39310×
    Ok(Ok(format!("Saved for {label}: {words}.")))
39416×
}
395
396
/// `POST /admin/runners/updates/policy`: one level's settings.
3978×
pub async fn save_policy(State(app): State<Shared>, viewer: Viewer, Form(f): Form<PolicyForm>) -> Result<Page<UpdatesPage>, Error> {
3988×
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
3998×
    let me = require_admin(&viewer, &shell)?;
4008×
    csrf(&viewer, &f.csrf_token, &shell)?;
4018×
    let outcome = apply_policy(&app, &me, &Reach::Site, &f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
4028×
    page_after(&app, shell, outcome).await
4038×
}
404
405
#[derive(Deserialize)]
406
pub struct GroupForm {
407
    #[serde(rename = "_csrf")]
408
    pub(crate) csrf_token: String,
409
    #[serde(default)]
410
    owner: String,
411
    #[serde(default)]
412
    name: String,
413
    /// `percent` or `chosen`.
414
    #[serde(default)]
415
    mode: String,
416
    #[serde(default)]
417
    percent: String,
418
    #[serde(default)]
419
    runner: Vec<i64>,
420
    /// Its wave (oxygenflow#84), 1 to 9; blank for none.
421
    #[serde(default)]
422
    wave: String,
423
}
424
425
/// The wave a form gives, or why it cannot be one.
4266×
fn wave_of(f: &GroupForm) -> Result<Option<i64>, String> {
4276×
    let w = f.wave.trim();
4286×
    if w.is_empty() {
4293×
        return Ok(None);
4303×
    }
4313×
    match w.parse::<i64>() {
4323×
        Ok(n) if (1..=9).contains(&n) => Ok(Some(n)),
4331×
        _ => Err("A wave is a whole number from 1 to 9, or blank for after every wave.".into()),
434
    }
4356×
}
436
437
/// The percentage a form gives, or why it cannot be one.
4387×
fn percent_of(f: &GroupForm) -> Result<Option<i64>, String> {
4397×
    if f.mode != "percent" {
4405×
        return Ok(None);
4412×
    }
4422×
    match f.percent.trim().trim_end_matches('%').parse::<i64>() {
4432×
        Ok(p) if (1..=100).contains(&p) => Ok(Some(p)),
4441×
        _ => Err("A percentage is a whole number from 1 to 100.".into()),
445
    }
4467×
}
447
448
/// The chosen runners a form names that `owner`'s group may hold.
4494×
async fn chosen_in_reach(app: &Shared, owner: &str, f: &GroupForm) -> sqlx::Result<Vec<i64>> {
4504×
    let all = runners::list(&app.db).await?;
4519×
    Ok(f.runner.iter().copied().filter(|id| all.iter().any(|r| r.id == *id && (owner.is_empty() || r.scope_owner == owner))).collect())
4524×
}
453
454
/// Make a test group, within `reach` (an organisation's are its own).
4556×
pub async fn apply_create_group(app: &Shared, me: &accounts::Account, reach: &Reach, f: &GroupForm) -> sqlx::Result<Outcome> {
4566×
    let name = f.name.trim().to_string();
4576×
    if name.is_empty() || name.len() > 60 {
4580×
        return Ok(Err("A test group needs a name of up to 60 characters.".into()));
4596×
    }
4606×
    let owner = match reach {
4615×
        Reach::Site => f.owner.trim().to_string(),
4621×
        Reach::Org(o) => o.clone(),
463
    };
4646×
    if !owner.is_empty()
4651×
        && accounts::account_by_name(&app.db, &owner).await?.is_none()
4661×
        && accounts::org_by_name(&app.db, &owner).await?.is_none()
467
    {
4680×
        return Ok(Err(format!("There is no account or organisation {owner:?}.")));
4696×
    }
4706×
    let percent = match percent_of(f) {
4715×
        Ok(p) => p,
4721×
        Err(why) => return Ok(Err(why)),
473
    };
4745×
    if rdb::groups(&app.db).await?.iter().any(|g| g.owner == owner && g.name == name) {
4750×
        return Ok(Err(format!("There is already a test group {name:?} for those runners.")));
4765×
    }
4775×
    let wave = match wave_of(f) {
4784×
        Ok(w) => w,
4791×
        Err(why) => return Ok(Err(why)),
480
    };
4814×
    let chosen = chosen_in_reach(app, &owner, f).await?;
4824×
    let g = rdb::create_group(&app.db, &owner, &name, percent).await?;
4834×
    rdb::set_wave(&app.db, g.id, wave).await?;
4844×
    if percent.is_none() {
4854×
        rdb::set_members(&app.db, g.id, &chosen).await?;
4860×
    }
4874×
    let mut what = match percent {
4880×
        Some(p) => format!("{p}% of {}", if owner.is_empty() { "the site's runners".into() } else { format!("{owner}'s runners") }),
4894×
        None => format!("{} chosen runners", chosen.len()),
490
    };
4914×
    if let Some(w) = wave {
4922×
        what.push_str(&format!(", wave {w}"));
4932×
    }
4944×
    accounts::audit(&app.db, Some(me), "runner.updates.group", &name, &format!("created: {what}")).await.ok();
4954×
    Ok(Ok(format!("Test group {name} made: {what}. Give it its settings below.")))
4966×
}
497
498
/// `POST /admin/runners/updates/groups`: a new test group.
4995×
pub async fn create_group(
5005×
    State(app): State<Shared>,
5015×
    viewer: Viewer,
5025×
    axum_extra::extract::Form(f): axum_extra::extract::Form<GroupForm>,
5035×
) -> Result<Page<UpdatesPage>, Error> {
5045×
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
5055×
    let me = require_admin(&viewer, &shell)?;
5065×
    csrf(&viewer, &f.csrf_token, &shell)?;
5075×
    let outcome = apply_create_group(&app, &me, &Reach::Site, &f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5085×
    page_after(&app, shell, outcome).await
5095×
}
510
511
/// Set who is in test group `id`, within `reach`.
5121×
pub async fn apply_save_group(app: &Shared, me: &accounts::Account, reach: &Reach, id: i64, f: &GroupForm) -> sqlx::Result<Outcome> {
5131×
    let Some(g) = rdb::group(&app.db, id).await?.filter(|g| reach.holds_group(g)) else {
5140×
        return Ok(Err("That test group is gone.".into()));
515
    };
5161×
    let percent = match percent_of(f) {
5171×
        Ok(p) => p,
5180×
        Err(why) => return Ok(Err(why)),
519
    };
5201×
    let wave = match wave_of(f) {
5211×
        Ok(w) => w,
5220×
        Err(why) => return Ok(Err(why)),
523
    };
5241×
    let chosen = if percent.is_some() { vec![] } else { chosen_in_reach(app, &g.owner, f).await? };
5251×
    rdb::set_percent(&app.db, id, percent).await?;
5261×
    rdb::set_members(&app.db, id, &chosen).await?;
5271×
    rdb::set_wave(&app.db, id, wave).await?;
5281×
    let mut what = match percent {
5291×
        Some(p) => format!("{p}% of its runners"),
5300×
        None => format!("{} chosen runners", chosen.len()),
531
    };
5321×
    if let Some(w) = wave {
5330×
        what.push_str(&format!(" in wave {w}"));
5341×
    }
5351×
    accounts::audit(&app.db, Some(me), "runner.updates.group", &g.name, &what).await.ok();
5361×
    Ok(Ok(format!("Test group {} is now {what}.", g.name)))
5371×
}
538
539
/// `POST /admin/runners/updates/groups/{id}`: who is in a test group.
5401×
pub async fn save_group(
5411×
    State(app): State<Shared>,
5421×
    viewer: Viewer,
5431×
    Path(id): Path<i64>,
5441×
    axum_extra::extract::Form(f): axum_extra::extract::Form<GroupForm>,
5451×
) -> Result<Page<UpdatesPage>, Error> {
5461×
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
5471×
    let me = require_admin(&viewer, &shell)?;
5481×
    csrf(&viewer, &f.csrf_token, &shell)?;
5491×
    let outcome = apply_save_group(&app, &me, &Reach::Site, id, &f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5501×
    page_after(&app, shell, outcome).await
5511×
}
552
553
#[derive(Deserialize)]
554
pub struct CsrfOnly {
555
    #[serde(rename = "_csrf")]
556
    pub(crate) csrf_token: String,
557
}
558
559
/// Remove test group `id`, within `reach`.
5602×
pub async fn apply_delete_group(app: &Shared, me: &accounts::Account, reach: &Reach, id: i64) -> sqlx::Result<Outcome> {
5612×
    let Some(g) = rdb::group(&app.db, id).await?.filter(|g| reach.holds_group(g)) else {
5621×
        return Ok(Err("That test group is gone.".into()));
563
    };
5641×
    rdb::delete_group(&app.db, id).await?;
5651×
    accounts::audit(&app.db, Some(me), "runner.updates.group", &g.name, "removed").await.ok();
5661×
    Ok(Ok(format!("Test group {} removed; its runners follow the levels above it.", g.name)))
5672×
}
568
569
/// `POST /admin/runners/updates/groups/{id}/delete`.
5701×
pub async fn delete_group(
5711×
    State(app): State<Shared>,
5721×
    viewer: Viewer,
5731×
    Path(id): Path<i64>,
5741×
    Form(f): Form<CsrfOnly>,
5751×
) -> Result<Page<UpdatesPage>, Error> {
5761×
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
5771×
    let me = require_admin(&viewer, &shell)?;
5781×
    csrf(&viewer, &f.csrf_token, &shell)?;
5791×
    let outcome = apply_delete_group(&app, &me, &Reach::Site, id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5801×
    page_after(&app, shell, outcome).await
5811×
}
582
583
#[derive(Deserialize)]
584
pub struct LiftForm {
585
    #[serde(rename = "_csrf")]
586
    csrf_token: String,
587
    version: String,
588
}
589
590
/// `POST /admin/runners/updates/holds/lift`: offer a held build again (#326).
5912×
pub async fn lift_hold(State(app): State<Shared>, viewer: Viewer, Form(f): Form<LiftForm>) -> Result<Page<UpdatesPage>, Error> {
5922×
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
5932×
    let me = require_admin(&viewer, &shell)?;
5942×
    csrf(&viewer, &f.csrf_token, &shell)?;
5952×
    let v = f.version.trim();
5962×
    if !rdb::lift(&app.db, v).await.map_err(|e| Error::from_db(shell.clone(), e))? {
5971×
        return page(&app, shell, None, Some(format!("flow {v} is not held."))).await;
5981×
    }
5991×
    accounts::audit(&app.db, Some(&me), "runner.update.lifted", v, "offered again").await.ok();
6001×
    page(&app, shell, Some(format!("flow {v} is offered again where the settings say so.")), None).await
6012×
}