OXYGENHUB
# 356183b71fab oxygenhub / crates / hub / src / api / backups.rs
7.1 KiB · Rust · last changed Backups API: settings, TEST, back up now and runs 22 days ago source blame history raw
2e9188ca Andy McCall ↶ 1
//! The backups API (oxygenhub#179, docs/backups.md §5): what the Backups
2
//! pages do, for a user's own repositories and an organisation's (its
3
//! owners only), with the scope `repo:admin`.
4
5
use super::{caller, not_found, ApiError, Caller};
6
use crate::auth;
7
use crate::backups::{self, Run, Setting};
8
use crate::db::{self, accounts::Account};
9
use crate::web::backups::{setting_of, SettingInput};
10
use crate::Shared;
11
use axum::extract::{Path, State};
12
use axum::http::{HeaderMap, StatusCode};
13
use axum::Json;
14
use serde::{Deserialize, Serialize};
15
16
/// A setting as the API takes it: the page's fields, `keep_days` a number.
17
#[derive(Deserialize)]
18
pub struct Body {
19
    pub every: String,
20
    #[serde(default)]
21
    pub destination: String,
22
    /// A directory destination: one the hub allows.
23
    #[serde(default)]
24
    pub dir: String,
25
    /// A GCS destination: its bucket and workload identity provider.
26
    #[serde(default)]
27
    pub bucket: String,
28
    #[serde(default)]
29
    pub provider: String,
30
    #[serde(default)]
31
    pub prefix: String,
32
    #[serde(default = "thirty")]
33
    pub keep_days: i64,
34
    /// An S3 destination: its bucket, region and the IAM role's ARN.
35
    #[serde(default)]
36
    pub s3_bucket: String,
37
    #[serde(default)]
38
    pub s3_region: String,
39
    #[serde(default)]
40
    pub s3_role: String,
41
}
42
43
fn thirty() -> i64 {
44
    30
45
}
46
47
#[derive(Serialize)]
48
pub struct State_ {
49
    pub setting: Option<Setting>,
50
    /// Where its runs go, as the pages say it.
51
    pub place: Option<String>,
52
    pub runs: Vec<Run>,
53
}
54
55
/// The owner a call acts for: the caller's own account, or an organisation
56
/// it owns. Someone else's is not found.
57
async fn owner_of(app: &Shared, c: &Caller, org: Option<&str>) -> Result<(Account, String, &'static str), ApiError> {
58
    let me = c.require("repo:admin")?.clone();
59
    match org {
60
        None => {
61
            let name = me.username.clone();
62
            Ok((me, name, "user"))
63
        }
64
        Some(name) => {
65
            let o = db::accounts::org_by_name(&app.db, name).await?.ok_or_else(|| not_found("no such organisation"))?;
66
            if !auth::roles::is_org_owner(&app.db, &me, o.id).await? {
67
                return Err(not_found("no such organisation"));
68
            }
69
            Ok((me, o.name, "org"))
70
        }
71
    }
72
}
73
74
async fn state(app: &Shared, owner: &str) -> Result<State_, ApiError> {
75
    let setting = backups::setting(&app.db, owner).await?;
76
    let place = setting.as_ref().map(backups::place);
77
    Ok(State_ { setting, place, runs: backups::runs(&app.db, owner, 10).await? })
78
}
79
80
async fn get(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<Json<State_>, ApiError> {
81
    let c = caller(&app, &headers).await?;
82
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
83
    Ok(Json(state(&app, &owner).await?))
84
}
85
86
async fn put(app: Shared, headers: HeaderMap, org: Option<String>, b: Body) -> Result<Json<State_>, ApiError> {
87
    let c = caller(&app, &headers).await?;
88
    let (me, owner, kind) = owner_of(&app, &c, org.as_deref()).await?;
89
    let input = SettingInput {
90
        every: b.every,
91
        destination: b.destination,
92
        dir: b.dir,
93
        bucket: b.bucket,
94
        provider: b.provider,
95
        prefix: b.prefix,
96
        keep_days: b.keep_days.to_string(),
97
        s3_bucket: b.s3_bucket,
98
        s3_region: b.s3_region,
99
        s3_role: b.s3_role,
100
    };
101
    let s = setting_of(&app, &owner, kind, &input).map_err(|e| ApiError(StatusCode::BAD_REQUEST, e))?;
102
    backups::save(&app.db, &s).await?;
103
    db::accounts::audit(&app.db, Some(&me), "backup.setting", &owner, &format!("{} to {}", s.every, backups::place(&s))).await.ok();
104
    Ok(Json(state(&app, &owner).await?))
105
}
106
107
async fn test(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<Json<serde_json::Value>, ApiError> {
108
    let c = caller(&app, &headers).await?;
109
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
110
    let set =
111
        backups::setting(&app.db, &owner).await?.ok_or_else(|| ApiError(StatusCode::CONFLICT, "save where backups go first".into()))?;
112
    let dest = backups::destination(&app, &set).map_err(|e| ApiError(StatusCode::CONFLICT, format!("{e:#}")))?;
113
    tokio::task::spawn_blocking(move || backups::probe(dest.as_ref()))
114
        .await
115
        .map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
116
        .map_err(|e| ApiError(StatusCode::CONFLICT, format!("TEST failed: {e:#}")))?;
117
    Ok(Json(serde_json::json!({ "ok": true, "place": backups::place(&set) })))
118
}
119
120
async fn run(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
121
    let c = caller(&app, &headers).await?;
122
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
123
    if backups::setting(&app.db, &owner).await?.is_none() {
124
        return Err(ApiError(StatusCode::CONFLICT, "save where backups go first".into()));
125
    }
126
    let (app2, owner2) = (app.clone(), owner.clone());
127
    tokio::spawn(async move {
128
        if let Err(e) = backups::run(&app2, &owner2, "now").await {
129
            tracing::warn!("backup of {owner2}: {e:#}");
130
        }
131
    });
132
    Ok((StatusCode::ACCEPTED, Json(serde_json::json!({ "owner": owner, "started": true }))))
133
}
134
135
async fn runs(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<Json<Vec<Run>>, ApiError> {
136
    let c = caller(&app, &headers).await?;
137
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
138
    Ok(Json(backups::runs(&app.db, &owner, 50).await?))
139
}
140
141
pub async fn user_get(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<State_>, ApiError> {
142
    get(app, headers, None).await
143
}
144
pub async fn user_put(State(app): State<Shared>, headers: HeaderMap, Json(b): Json<Body>) -> Result<Json<State_>, ApiError> {
145
    put(app, headers, None, b).await
146
}
147
pub async fn user_test(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<serde_json::Value>, ApiError> {
148
    test(app, headers, None).await
149
}
150
pub async fn user_run(State(app): State<Shared>, headers: HeaderMap) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
151
    run(app, headers, None).await
152
}
153
pub async fn user_runs(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<Run>>, ApiError> {
154
    runs(app, headers, None).await
155
}
156
pub async fn org_get(State(app): State<Shared>, headers: HeaderMap, Path(name): Path<String>) -> Result<Json<State_>, ApiError> {
157
    get(app, headers, Some(name)).await
158
}
159
pub async fn org_put(
160
    State(app): State<Shared>,
161
    headers: HeaderMap,
162
    Path(name): Path<String>,
163
    Json(b): Json<Body>,
164
) -> Result<Json<State_>, ApiError> {
165
    put(app, headers, Some(name), b).await
166
}
167
pub async fn org_test(
168
    State(app): State<Shared>,
169
    headers: HeaderMap,
170
    Path(name): Path<String>,
171
) -> Result<Json<serde_json::Value>, ApiError> {
172
    test(app, headers, Some(name)).await
173
}
174
pub async fn org_run(
175
    State(app): State<Shared>,
176
    headers: HeaderMap,
177
    Path(name): Path<String>,
178
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
179
    run(app, headers, Some(name)).await
180
}
181
pub async fn org_runs(State(app): State<Shared>, headers: HeaderMap, Path(name): Path<String>) -> Result<Json<Vec<Run>>, ApiError> {
182
    runs(app, headers, Some(name)).await
183
}