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