OXYGENHUB
◆ v0.9.6 oxygenhub / crates / hub / src / web / runner_updates.rs
20.3 KiB · Rust · last changed oh runner-updates and the admin API for runner updates 10 days ago source blame history raw
8501fd58 Andy McCall ↶ 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
18
fn require_admin(viewer: &Viewer, shell: &Shell) -> Result<accounts::Account, Error> {
19
    match viewer.account() {
20
        Some(a) if a.is_admin => Ok(a.clone()),
21
        _ => Err(Error::not_found(shell.clone())),
22
    }
23
}
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 {
38
    fn of(p: &Policy, label: String) -> PolicyView {
39
        let tri = |b: Option<bool>| match b {
40
            Some(true) => "on",
41
            Some(false) => "off",
42
            None => "inherit",
43
        };
44
        PolicyView {
45
            scope: p.scope.clone(),
46
            key: p.key.clone(),
47
            label,
48
            updates: tri(p.updates),
49
            channel: p.channel.clone().unwrap_or_default(),
50
            window: match (p.window_from, p.window_to) {
51
                (Some(a), Some(b)) => format!("{a:02}-{b:02}"),
52
                _ => String::new(),
53
            },
54
            dry_run: tri(p.dry_run),
55
        }
56
    }
57
58
    /// The settings in words, for a table.
59
    pub fn summary(&self) -> String {
60
        let mut s = vec![];
61
        if self.updates != "inherit" {
62
            s.push(format!("updates {}", self.updates));
63
        }
64
        if !self.channel.is_empty() {
65
            s.push(format!("channel {}", self.channel));
66
        }
67
        if !self.window.is_empty() {
68
            s.push(format!("window {} UTC", self.window));
69
        }
70
        if self.dry_run != "inherit" {
71
            s.push(format!("dry run {}", self.dry_run));
72
        }
73
        if s.is_empty() {
74
            "inherits everything".into()
75
        } else {
76
            s.join(", ")
77
        }
78
    }
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.
102
    pub fn effective_words(&self) -> String {
103
        let e = &self.effective;
104
        let mut s = vec![format!("updates {} ({})", if e.updates { "on" } else { "off" }, e.from[0])];
105
        if e.updates {
106
            s.push(format!("channel {} ({})", e.channel, e.from[1]));
107
            if let Some((a, b)) = e.window {
108
                s.push(format!("window {a:02}–{b:02} UTC ({})", e.from[2]));
109
            }
110
            if e.dry_run {
111
                s.push(format!("dry run ({})", e.from[3]));
112
            }
113
        }
114
        s.join(" · ")
115
    }
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>,
faf5246c Andy McCall ↶ 127
    /// Builds held back after rolling back on a runner (#326).
128
    holds: Vec<rdb::Hold>,
8501fd58 Andy McCall ↶ 129
    notice: Option<String>,
130
    error: Option<String>,
131
}
132
dc5c6429 Andy McCall ↶ 133
/// Who changes runner updates: the site's administrators anything; an
134
/// organisation's owners their organisation's setting, its test groups and
135
/// its runners (Andy: an organisation tries a build on some of its runners
136
/// before the rest).
137
#[derive(Clone, Debug, PartialEq, Eq)]
138
pub enum Reach {
139
    Site,
140
    Org(String),
141
}
142
143
impl Reach {
144
    fn holds_runner(&self, r: &runners::Runner) -> bool {
145
        match self {
146
            Reach::Site => true,
147
            Reach::Org(o) => r.scope_owner == *o,
148
        }
149
    }
150
151
    fn holds_group(&self, g: &Group) -> bool {
152
        match self {
153
            Reach::Site => true,
154
            Reach::Org(o) => g.owner == *o,
155
        }
156
    }
157
}
158
159
/// What a page shows of runner updates, within `reach`.
160
pub struct UpdateViews {
161
    pub site: PolicyView,
162
    pub owners: Vec<PolicyView>,
163
    pub groups: Vec<GroupView>,
164
    pub runners: Vec<RunnerView>,
165
}
166
167
pub async fn views(app: &Shared, reach: &Reach) -> sqlx::Result<UpdateViews> {
168
    let levels = Levels::load(&app.db).await?;
169
    let all = runners::list(&app.db).await?;
8501fd58 Andy McCall ↶ 170
    let policy = |scope: &str, key: &str| {
171
        levels.policies.get(&(scope.to_string(), key.to_string())).cloned().unwrap_or(Policy {
172
            scope: scope.into(),
173
            key: key.into(),
174
            ..Policy::default()
175
        })
dc5c6429 Andy McCall ↶ 176
    };
177
    let mut owners: Vec<PolicyView> = match reach {
178
        Reach::Site => {
179
            levels.policies.values().filter(|p| p.scope == "owner").map(|p| PolicyView::of(p, format!("owner {}", p.key))).collect()
180
        }
181
        Reach::Org(o) => vec![PolicyView::of(&policy("owner", o), format!("owner {o}"))],
8501fd58 Andy McCall ↶ 182
    };
183
    owners.sort_by(|a, b| a.key.cmp(&b.key));
184
    let groups = levels
185
        .groups
186
        .iter()
dc5c6429 Andy McCall ↶ 187
        .filter(|g| reach.holds_group(g))
8501fd58 Andy McCall ↶ 188
        .map(|g| GroupView {
189
            g: g.clone(),
190
            reach: if g.owner.is_empty() { "the site's runners".into() } else { format!("{}'s runners", g.owner) },
191
            members: all.iter().filter(|r| levels.member(g, r)).map(|r| r.name.clone()).collect(),
192
            chosen: levels.chosen.iter().filter(|(gid, _)| *gid == g.id).map(|(_, r)| *r).collect(),
193
            policy: PolicyView::of(&policy("group", &g.id.to_string()), format!("group {}", g.name)),
194
        })
195
        .collect();
196
    let hour = time::OffsetDateTime::now_utc().hour();
dc5c6429 Andy McCall ↶ 197
    let mut out = vec![];
198
    for r in all.into_iter().filter(|r| reach.holds_runner(r)) {
8501fd58 Andy McCall ↶ 199
        let effective = levels.resolve(&r);
dc5c6429 Andy McCall ↶ 200
        let (_, offer) = ru::offer(&app.db, &r, &effective, hour).await?;
201
        out.push(RunnerView {
8501fd58 Andy McCall ↶ 202
            groups: levels.groups_of(&r).iter().map(|g| g.name.clone()).collect(),
203
            policy: PolicyView::of(&policy("runner", &r.id.to_string()), format!("runner {}", r.name)),
204
            effective,
205
            offer,
206
            r,
207
        });
dc5c6429 Andy McCall ↶ 208
    }
209
    Ok(UpdateViews { site: PolicyView::of(&policy("site", ""), "the site".into()), owners, groups, runners: out })
210
}
211
212
async fn page(app: &Shared, shell: Shell, notice: Option<String>, error: Option<String>) -> Result<Page<UpdatesPage>, Error> {
213
    let e = |e| Error::from_db(shell.clone(), e);
214
    let repo = accounts::setting(&app.db, ru::SETTING_REPO).await.map_err(e)?.unwrap_or_default();
215
    let v = views(app, &Reach::Site).await.map_err(e)?;
faf5246c Andy McCall ↶ 216
    let holds = rdb::holds(&app.db).await.map_err(e)?;
217
    Ok(Page(UpdatesPage { shell, repo, site: v.site, owners: v.owners, groups: v.groups, runners: v.runners, holds, notice, error }))
dc5c6429 Andy McCall ↶ 218
}
219
220
/// What a change did, to say on the page: `Ok` a notice, `Err` what was wrong.
221
pub type Outcome = Result<String, String>;
222
223
/// [`page`] saying what `outcome` did.
224
async fn page_after(app: &Shared, shell: Shell, outcome: Outcome) -> Result<Page<UpdatesPage>, Error> {
225
    match outcome {
226
        Ok(n) => page(app, shell, Some(n), None).await,
227
        Err(why) => page(app, shell, None, Some(why)).await,
8501fd58 Andy McCall ↶ 228
    }
229
}
230
231
pub async fn show(State(app): State<Shared>, viewer: Viewer) -> Result<Page<UpdatesPage>, Error> {
232
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
233
    require_admin(&viewer, &shell)?;
234
    page(&app, shell, None, None).await
235
}
236
237
#[derive(Deserialize)]
238
pub struct SourceForm {
239
    #[serde(rename = "_csrf")]
240
    csrf_token: String,
241
    repo: String,
242
}
243
244
/// `POST /admin/runners/updates/source`: the repository whose releases carry runner builds.
245
pub async fn save_source(State(app): State<Shared>, viewer: Viewer, Form(f): Form<SourceForm>) -> Result<Page<UpdatesPage>, Error> {
246
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
247
    let me = require_admin(&viewer, &shell)?;
248
    csrf(&viewer, &f.csrf_token, &shell)?;
249
    let repo = f.repo.trim().trim_matches('/').to_string();
250
    if !repo.is_empty() {
251
        let found = match repo.split_once('/') {
252
            Some((o, n)) => crate::db::repos::get(&app.db, o, n).await.map_err(|e| Error::from_db(shell.clone(), e))?,
253
            None => None,
254
        };
255
        if found.is_none() {
256
            return page(&app, shell, None, Some(format!("There is no repository {repo:?} here; give it as owner/name."))).await;
257
        }
258
    }
259
    accounts::set_setting(&app.db, ru::SETTING_REPO, &repo).await.map_err(|e| Error::from_db(shell.clone(), e))?;
260
    accounts::audit(&app.db, Some(&me), "runner.updates.source", &repo, "runner builds come from its releases").await.ok();
261
    let n = if repo.is_empty() {
262
        "Saved: no repository, so no runner is offered a build.".into()
263
    } else {
264
        format!("Saved: runner builds come from {repo}'s releases.")
265
    };
266
    page(&app, shell, Some(n), None).await
267
}
268
269
#[derive(Deserialize)]
270
pub struct PolicyForm {
271
    #[serde(rename = "_csrf")]
dc5c6429 Andy McCall ↶ 272
    pub(crate) csrf_token: String,
8501fd58 Andy McCall ↶ 273
    scope: String,
274
    #[serde(default)]
275
    key: String,
276
    #[serde(default)]
277
    updates: String,
278
    #[serde(default)]
279
    channel: String,
280
    #[serde(default)]
281
    window: String,
282
    #[serde(default)]
283
    dry_run: String,
284
}
285
9bbca80f Andy McCall ↶ 286
impl PolicyForm {
287
    /// The form an API setting stands for.
288
    pub fn of(u: &hub_api::UpdateSetting) -> PolicyForm {
289
        let tri = |b: Option<bool>| match b {
290
            Some(true) => "on",
291
            Some(false) => "off",
292
            None => "inherit",
293
        };
294
        PolicyForm {
295
            csrf_token: String::new(),
296
            scope: u.scope.clone(),
297
            key: u.key.clone(),
298
            updates: tri(u.updates).into(),
299
            channel: u.channel.clone().unwrap_or_default(),
300
            window: u.window.clone().unwrap_or_default(),
301
            dry_run: tri(u.dry_run).into(),
302
        }
303
    }
304
}
305
dc5c6429 Andy McCall ↶ 306
/// Set one level's settings, within `reach`.
307
pub async fn apply_policy(app: &Shared, me: &accounts::Account, reach: &Reach, f: &PolicyForm) -> sqlx::Result<Outcome> {
8501fd58 Andy McCall ↶ 308
    let key = f.key.trim().to_string();
dc5c6429 Andy McCall ↶ 309
    let label = match (f.scope.as_str(), reach) {
310
        ("site", Reach::Site) if key.is_empty() => "the site".to_string(),
311
        ("owner", Reach::Org(o)) if key != *o => return Ok(Err("An organisation sets its own runners' updates only.".into())),
312
        ("owner", _) => {
313
            let known = accounts::account_by_name(&app.db, &key).await?.is_some() || accounts::org_by_name(&app.db, &key).await?.is_some();
8501fd58 Andy McCall ↶ 314
            if !known {
dc5c6429 Andy McCall ↶ 315
                return Ok(Err(format!("There is no account or organisation {key:?}.")));
8501fd58 Andy McCall ↶ 316
            }
317
            format!("owner {key}")
318
        }
dc5c6429 Andy McCall ↶ 319
        ("group", _) => match key.parse().ok() {
320
            Some(id) => match rdb::group(&app.db, id).await?.filter(|g| reach.holds_group(g)) {
8501fd58 Andy McCall ↶ 321
                Some(g) => format!("group {}", g.name),
dc5c6429 Andy McCall ↶ 322
                None => return Ok(Err("That test group is gone.".into())),
8501fd58 Andy McCall ↶ 323
            },
dc5c6429 Andy McCall ↶ 324
            None => return Ok(Err("That test group is gone.".into())),
8501fd58 Andy McCall ↶ 325
        },
dc5c6429 Andy McCall ↶ 326
        ("runner", _) => match key.parse().ok() {
327
            Some(id) => match runners::get(&app.db, id).await?.filter(|r| reach.holds_runner(r)) {
8501fd58 Andy McCall ↶ 328
                Some(r) => format!("runner {}", r.name),
dc5c6429 Andy McCall ↶ 329
                None => return Ok(Err("That runner is gone.".into())),
8501fd58 Andy McCall ↶ 330
            },
dc5c6429 Andy McCall ↶ 331
            None => return Ok(Err("That runner is gone.".into())),
8501fd58 Andy McCall ↶ 332
        },
dc5c6429 Andy McCall ↶ 333
        _ => return Ok(Err("Choose the site, an owner, a test group or a runner.".into())),
8501fd58 Andy McCall ↶ 334
    };
335
    let tri = |v: &str| match v {
336
        "on" => Some(true),
337
        "off" => Some(false),
338
        _ => None,
339
    };
340
    let channel = f.channel.trim().to_string();
341
    if !channel.is_empty() && !ru::valid_channel(&channel) {
dc5c6429 Andy McCall ↶ 342
        return Ok(Err(format!("A channel is stable, canary or a version such as 0.3.4, not {channel:?}.")));
8501fd58 Andy McCall ↶ 343
    }
344
    let window = match ru::parse_window(&f.window) {
345
        Ok(w) => w,
dc5c6429 Andy McCall ↶ 346
        Err(why) => return Ok(Err(format!("{why}."))),
8501fd58 Andy McCall ↶ 347
    };
348
    let p = Policy {
349
        scope: f.scope.clone(),
350
        key,
351
        updates: tri(&f.updates),
352
        channel: Some(channel).filter(|c| !c.is_empty()),
353
        window_from: window.map(|w| w.0 as i64),
354
        window_to: window.map(|w| w.1 as i64),
355
        dry_run: tri(&f.dry_run),
356
    };
dc5c6429 Andy McCall ↶ 357
    rdb::set_policy(&app.db, &p).await?;
8501fd58 Andy McCall ↶ 358
    let words = PolicyView::of(&p, label.clone()).summary();
dc5c6429 Andy McCall ↶ 359
    accounts::audit(&app.db, Some(me), "runner.updates.policy", &label, &words).await.ok();
360
    Ok(Ok(format!("Saved for {label}: {words}.")))
361
}
362
363
/// `POST /admin/runners/updates/policy`: one level's settings.
364
pub async fn save_policy(State(app): State<Shared>, viewer: Viewer, Form(f): Form<PolicyForm>) -> Result<Page<UpdatesPage>, Error> {
365
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
366
    let me = require_admin(&viewer, &shell)?;
367
    csrf(&viewer, &f.csrf_token, &shell)?;
368
    let outcome = apply_policy(&app, &me, &Reach::Site, &f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
369
    page_after(&app, shell, outcome).await
8501fd58 Andy McCall ↶ 370
}
371
372
#[derive(Deserialize)]
373
pub struct GroupForm {
374
    #[serde(rename = "_csrf")]
dc5c6429 Andy McCall ↶ 375
    pub(crate) csrf_token: String,
8501fd58 Andy McCall ↶ 376
    #[serde(default)]
377
    owner: String,
378
    #[serde(default)]
379
    name: String,
380
    /// `percent` or `chosen`.
381
    #[serde(default)]
382
    mode: String,
383
    #[serde(default)]
384
    percent: String,
385
    #[serde(default)]
386
    runner: Vec<i64>,
387
}
388
389
/// The percentage a form gives, or why it cannot be one.
390
fn percent_of(f: &GroupForm) -> Result<Option<i64>, String> {
391
    if f.mode != "percent" {
392
        return Ok(None);
393
    }
394
    match f.percent.trim().trim_end_matches('%').parse::<i64>() {
395
        Ok(p) if (1..=100).contains(&p) => Ok(Some(p)),
396
        _ => Err("A percentage is a whole number from 1 to 100.".into()),
397
    }
398
}
399
dc5c6429 Andy McCall ↶ 400
/// The chosen runners a form names that `owner`'s group may hold.
401
async fn chosen_in_reach(app: &Shared, owner: &str, f: &GroupForm) -> sqlx::Result<Vec<i64>> {
402
    let all = runners::list(&app.db).await?;
403
    Ok(f.runner.iter().copied().filter(|id| all.iter().any(|r| r.id == *id && (owner.is_empty() || r.scope_owner == owner))).collect())
404
}
405
406
/// Make a test group, within `reach` (an organisation's are its own).
407
pub async fn apply_create_group(app: &Shared, me: &accounts::Account, reach: &Reach, f: &GroupForm) -> sqlx::Result<Outcome> {
8501fd58 Andy McCall ↶ 408
    let name = f.name.trim().to_string();
409
    if name.is_empty() || name.len() > 60 {
dc5c6429 Andy McCall ↶ 410
        return Ok(Err("A test group needs a name of up to 60 characters.".into()));
8501fd58 Andy McCall ↶ 411
    }
dc5c6429 Andy McCall ↶ 412
    let owner = match reach {
413
        Reach::Site => f.owner.trim().to_string(),
414
        Reach::Org(o) => o.clone(),
415
    };
8501fd58 Andy McCall ↶ 416
    if !owner.is_empty()
dc5c6429 Andy McCall ↶ 417
        && accounts::account_by_name(&app.db, &owner).await?.is_none()
418
        && accounts::org_by_name(&app.db, &owner).await?.is_none()
8501fd58 Andy McCall ↶ 419
    {
dc5c6429 Andy McCall ↶ 420
        return Ok(Err(format!("There is no account or organisation {owner:?}.")));
8501fd58 Andy McCall ↶ 421
    }
dc5c6429 Andy McCall ↶ 422
    let percent = match percent_of(f) {
8501fd58 Andy McCall ↶ 423
        Ok(p) => p,
dc5c6429 Andy McCall ↶ 424
        Err(why) => return Ok(Err(why)),
8501fd58 Andy McCall ↶ 425
    };
dc5c6429 Andy McCall ↶ 426
    if rdb::groups(&app.db).await?.iter().any(|g| g.owner == owner && g.name == name) {
427
        return Ok(Err(format!("There is already a test group {name:?} for those runners.")));
8501fd58 Andy McCall ↶ 428
    }
dc5c6429 Andy McCall ↶ 429
    let chosen = chosen_in_reach(app, &owner, f).await?;
430
    let g = rdb::create_group(&app.db, &owner, &name, percent).await?;
8501fd58 Andy McCall ↶ 431
    if percent.is_none() {
dc5c6429 Andy McCall ↶ 432
        rdb::set_members(&app.db, g.id, &chosen).await?;
8501fd58 Andy McCall ↶ 433
    }
434
    let what = match percent {
435
        Some(p) => format!("{p}% of {}", if owner.is_empty() { "the site's runners".into() } else { format!("{owner}'s runners") }),
dc5c6429 Andy McCall ↶ 436
        None => format!("{} chosen runners", chosen.len()),
8501fd58 Andy McCall ↶ 437
    };
dc5c6429 Andy McCall ↶ 438
    accounts::audit(&app.db, Some(me), "runner.updates.group", &name, &format!("created: {what}")).await.ok();
439
    Ok(Ok(format!("Test group {name} made: {what}. Give it its settings below.")))
8501fd58 Andy McCall ↶ 440
}
441
dc5c6429 Andy McCall ↶ 442
/// `POST /admin/runners/updates/groups`: a new test group.
443
pub async fn create_group(
8501fd58 Andy McCall ↶ 444
    State(app): State<Shared>,
445
    viewer: Viewer,
446
    axum_extra::extract::Form(f): axum_extra::extract::Form<GroupForm>,
447
) -> Result<Page<UpdatesPage>, Error> {
448
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
449
    let me = require_admin(&viewer, &shell)?;
450
    csrf(&viewer, &f.csrf_token, &shell)?;
dc5c6429 Andy McCall ↶ 451
    let outcome = apply_create_group(&app, &me, &Reach::Site, &f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
452
    page_after(&app, shell, outcome).await
453
}
454
455
/// Set who is in test group `id`, within `reach`.
456
pub async fn apply_save_group(app: &Shared, me: &accounts::Account, reach: &Reach, id: i64, f: &GroupForm) -> sqlx::Result<Outcome> {
457
    let Some(g) = rdb::group(&app.db, id).await?.filter(|g| reach.holds_group(g)) else {
458
        return Ok(Err("That test group is gone.".into()));
8501fd58 Andy McCall ↶ 459
    };
dc5c6429 Andy McCall ↶ 460
    let percent = match percent_of(f) {
8501fd58 Andy McCall ↶ 461
        Ok(p) => p,
dc5c6429 Andy McCall ↶ 462
        Err(why) => return Ok(Err(why)),
8501fd58 Andy McCall ↶ 463
    };
dc5c6429 Andy McCall ↶ 464
    let chosen = if percent.is_some() { vec![] } else { chosen_in_reach(app, &g.owner, f).await? };
465
    rdb::set_percent(&app.db, id, percent).await?;
466
    rdb::set_members(&app.db, id, &chosen).await?;
8501fd58 Andy McCall ↶ 467
    let what = match percent {
468
        Some(p) => format!("{p}% of its runners"),
dc5c6429 Andy McCall ↶ 469
        None => format!("{} chosen runners", chosen.len()),
8501fd58 Andy McCall ↶ 470
    };
dc5c6429 Andy McCall ↶ 471
    accounts::audit(&app.db, Some(me), "runner.updates.group", &g.name, &what).await.ok();
472
    Ok(Ok(format!("Test group {} is now {what}.", g.name)))
8501fd58 Andy McCall ↶ 473
}
474
dc5c6429 Andy McCall ↶ 475
/// `POST /admin/runners/updates/groups/{id}`: who is in a test group.
476
pub async fn save_group(
477
    State(app): State<Shared>,
478
    viewer: Viewer,
479
    Path(id): Path<i64>,
480
    axum_extra::extract::Form(f): axum_extra::extract::Form<GroupForm>,
481
) -> Result<Page<UpdatesPage>, Error> {
482
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
483
    let me = require_admin(&viewer, &shell)?;
484
    csrf(&viewer, &f.csrf_token, &shell)?;
485
    let outcome = apply_save_group(&app, &me, &Reach::Site, id, &f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
486
    page_after(&app, shell, outcome).await
487
}
488
8501fd58 Andy McCall ↶ 489
#[derive(Deserialize)]
490
pub struct CsrfOnly {
491
    #[serde(rename = "_csrf")]
dc5c6429 Andy McCall ↶ 492
    pub(crate) csrf_token: String,
8501fd58 Andy McCall ↶ 493
}
494
dc5c6429 Andy McCall ↶ 495
/// Remove test group `id`, within `reach`.
496
pub async fn apply_delete_group(app: &Shared, me: &accounts::Account, reach: &Reach, id: i64) -> sqlx::Result<Outcome> {
497
    let Some(g) = rdb::group(&app.db, id).await?.filter(|g| reach.holds_group(g)) else {
498
        return Ok(Err("That test group is gone.".into()));
499
    };
500
    rdb::delete_group(&app.db, id).await?;
501
    accounts::audit(&app.db, Some(me), "runner.updates.group", &g.name, "removed").await.ok();
502
    Ok(Ok(format!("Test group {} removed; its runners follow the levels above it.", g.name)))
503
}
504
8501fd58 Andy McCall ↶ 505
/// `POST /admin/runners/updates/groups/{id}/delete`.
506
pub async fn delete_group(
507
    State(app): State<Shared>,
508
    viewer: Viewer,
509
    Path(id): Path<i64>,
510
    Form(f): Form<CsrfOnly>,
511
) -> Result<Page<UpdatesPage>, Error> {
512
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
513
    let me = require_admin(&viewer, &shell)?;
514
    csrf(&viewer, &f.csrf_token, &shell)?;
dc5c6429 Andy McCall ↶ 515
    let outcome = apply_delete_group(&app, &me, &Reach::Site, id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
516
    page_after(&app, shell, outcome).await
8501fd58 Andy McCall ↶ 517
}
faf5246c Andy McCall ↶ 518
519
#[derive(Deserialize)]
520
pub struct LiftForm {
521
    #[serde(rename = "_csrf")]
522
    csrf_token: String,
523
    version: String,
524
}
525
526
/// `POST /admin/runners/updates/holds/lift`: offer a held build again (#326).
527
pub async fn lift_hold(State(app): State<Shared>, viewer: Viewer, Form(f): Form<LiftForm>) -> Result<Page<UpdatesPage>, Error> {
528
    let shell = Shell::new(&app, "/admin/runners/updates", &viewer);
529
    let me = require_admin(&viewer, &shell)?;
530
    csrf(&viewer, &f.csrf_token, &shell)?;
531
    let v = f.version.trim();
532
    if !rdb::lift(&app.db, v).await.map_err(|e| Error::from_db(shell.clone(), e))? {
533
        return page(&app, shell, None, Some(format!("flow {v} is not held."))).await;
534
    }
535
    accounts::audit(&app.db, Some(&me), "runner.update.lifted", v, "offered again").await.ok();
536
    page(&app, shell, Some(format!("flow {v} is offered again where the settings say so.")), None).await
537
}