OXYGENHUB
◆ v0.6.1 oxygenhub / crates / hub / src / backups.rs
85.0 KiB · Rust · last changed Drops: per-user gists, each a small hidden Oxygen repository (#279) 15 days ago source blame history raw
d7d18246 Andy McCall ↶ 1
//! Backups (docs/backups.md, oxygenhub#169): each user and organisation
2
//! copies its repositories, on a schedule, to a destination it controls.
3
//!
4
//! A repository is its store directory (`.oxy/`): packs and loose objects
5
//! that never change once written, and small files that do (refs, the
6
//! operation log, policies, signature indexes). A run copies each file
7
//! once, named by its BLAKE3 (`blobs/`), and writes a manifest of path to
8
//! hash per repository (`runs/<at>/repos/`), so only what changed travels
9
//! and any kept run can be restored byte for byte, signatures and all.
10
//! The large files are copied first; the walk is then repeated under the
11
//! repository's read lock, which pushes wait on, so each manifest is one
12
//! consistent moment. Beside each manifest go the hub's records for the
13
//! repository as JSON (never a secret value), the owner's records, and
14
//! last a `DONE` marker: a run without one was cut short and is ignored.
15
16
use crate::db::{self, Pool};
17
use crate::repos::RepoName;
18
use crate::Shared;
19
use anyhow::{bail, Context, Result};
20
use serde::{Deserialize, Serialize};
21
use std::collections::HashMap;
22
use std::path::{Path, PathBuf};
23
24
/// How often, as the settings offer it.
25
pub const EVERY: &[(&str, &str)] = &[("off", "Off"), ("hourly", "Every hour"), ("daily", "Every day")];
26
/// How long runs are kept, in days.
27
pub const KEEP: &[i64] = &[7, 30, 90];
28
29
/// What an owner backs up, where and how often.
30
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
31
pub struct Setting {
32
    pub owner: String,
33
    pub kind: String,
34
    pub every: String,
35
    pub destination: String,
36
    pub target: String,
37
    pub prefix: String,
38
    pub provider: String,
39
    pub keep_days: i64,
40
    pub updated_ms: i64,
7b9f4570 Andy McCall ↶ 41
    /// An S3 bucket's region (migration 0063).
42
    #[sqlx(default)]
43
    pub region: String,
d7d18246 Andy McCall ↶ 44
}
45
46
impl Setting {
47
    pub fn off(owner: &str, kind: &str) -> Setting {
48
        Setting {
49
            owner: owner.into(),
50
            kind: kind.into(),
51
            every: "off".into(),
52
            destination: "dir".into(),
53
            target: String::new(),
54
            prefix: String::new(),
55
            provider: String::new(),
56
            keep_days: 30,
57
            updated_ms: 0,
7b9f4570 Andy McCall ↶ 58
            region: String::new(),
d7d18246 Andy McCall ↶ 59
        }
60
    }
61
62
    /// Seconds between runs; none when off.
63
    pub fn period_s(&self) -> Option<i64> {
64
        match self.every.as_str() {
65
            "hourly" => Some(3600),
66
            "daily" => Some(86_400),
67
            _ => None,
68
        }
69
    }
70
}
71
72
/// One run, as the settings page and the API show it.
73
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
74
pub struct Run {
75
    pub id: i64,
76
    pub owner: String,
77
    pub started_ms: i64,
78
    pub finished_ms: Option<i64>,
79
    pub status: String,
80
    pub at: String,
81
    pub repos: i64,
82
    pub files: i64,
83
    pub sent: i64,
84
    pub bytes: i64,
85
    pub detail: String,
86
    pub trigger: String,
87
}
88
89
pub async fn setting(pool: &Pool, owner: &str) -> sqlx::Result<Option<Setting>> {
5d90e0e0 Andy McCall 90
    sqlx::query_as("SELECT * FROM backup_settings WHERE owner = $1").bind(owner).fetch_optional(pool).await
d7d18246 Andy McCall ↶ 91
}
92
93
pub async fn save(pool: &Pool, s: &Setting) -> sqlx::Result<()> {
94
    sqlx::query(
7b9f4570 Andy McCall ↶ 95
        "INSERT INTO backup_settings (owner, kind, every, destination, target, prefix, provider, keep_days, updated_ms, region) \
5d90e0e0 Andy McCall 96
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) ON CONFLICT(owner) DO UPDATE SET kind = excluded.kind, every = excluded.every, \
d7d18246 Andy McCall ↶ 97
         destination = excluded.destination, target = excluded.target, prefix = excluded.prefix, provider = excluded.provider, \
7b9f4570 Andy McCall ↶ 98
         keep_days = excluded.keep_days, updated_ms = excluded.updated_ms, region = excluded.region",
d7d18246 Andy McCall ↶ 99
    )
100
    .bind(&s.owner)
101
    .bind(&s.kind)
102
    .bind(&s.every)
103
    .bind(&s.destination)
104
    .bind(&s.target)
105
    .bind(&s.prefix)
106
    .bind(&s.provider)
107
    .bind(s.keep_days)
108
    .bind(db::now_ms())
7b9f4570 Andy McCall ↶ 109
    .bind(&s.region)
d7d18246 Andy McCall ↶ 110
    .execute(pool)
111
    .await?;
112
    Ok(())
113
}
114
115
pub async fn runs(pool: &Pool, owner: &str, limit: i64) -> sqlx::Result<Vec<Run>> {
5d90e0e0 Andy McCall 116
    sqlx::query_as("SELECT * FROM backup_runs WHERE owner = $1 ORDER BY id DESC LIMIT $2").bind(owner).bind(limit).fetch_all(pool).await
d7d18246 Andy McCall ↶ 117
}
118
d3b048b2 Andy McCall ↶ 119
/// What a repository may choose about its backup (§5): with its owner's,
120
/// left out, or at least hourly or daily whatever its owner's schedule.
121
pub const REPO_CHOICES: &[(&str, &str)] =
122
    &[("", "With its owner's backup"), ("hourly", "At least every hour"), ("daily", "At least every day"), ("off", "Left out")];
123
124
/// Whether `row` is in its owner's run: never when it is left out, always
125
/// when it has its own schedule, else as its owner's schedule says (a run
126
/// asked for by hand takes every repository not left out).
127
pub fn included(s: &Setting, row: &db::repos::RepoRow, by_hand: bool) -> bool {
128
    match row.backup.as_str() {
129
        "off" => false,
130
        "hourly" | "daily" => true,
131
        _ => by_hand || s.every != "off",
132
    }
133
}
134
135
/// Seconds between an owner's runs: the shortest of its own schedule and
136
/// its repositories' own; none when nothing is scheduled.
137
pub fn period_with(s: &Setting, repos: &[db::repos::RepoRow]) -> Option<i64> {
138
    let own = repos.iter().filter_map(|r| match r.backup.as_str() {
139
        "hourly" => Some(3600),
140
        "daily" => Some(86_400),
141
        _ => None,
142
    });
143
    s.period_s().into_iter().chain(own).min()
144
}
145
1e8a6e8b Andy McCall ↶ 146
/// One owner's backup as Admin › Backups shows it (§5): its setting, its
147
/// newest run, and how many runs failed in the last day. An administrator
148
/// sees that it ran, never what it wrote.
149
#[derive(Clone, Debug, Serialize)]
150
pub struct Overview {
151
    pub setting: Setting,
152
    pub last: Option<Run>,
153
    pub failed_day: i64,
154
    /// The repositories it covers now.
155
    pub repos: i64,
156
}
157
158
impl Overview {
159
    /// Where its runs go, as a person reads it.
160
    pub fn place(&self) -> String {
2e9188ca Andy McCall ↶ 161
        place(&self.setting)
162
    }
163
}
164
165
/// Where a setting's runs go, as a person reads it.
166
pub fn place(s: &Setting) -> String {
167
    match s.destination.as_str() {
168
        "gcs" if s.prefix.is_empty() => format!("gs://{}", s.target),
169
        "gcs" => format!("gs://{}/{}", s.target, s.prefix),
170
        "s3" if s.prefix.is_empty() => format!("s3://{} ({})", s.target, s.region),
171
        "s3" => format!("s3://{}/{} ({})", s.target, s.prefix, s.region),
172
        _ => format!("{}/{}", s.target, s.owner),
1e8a6e8b Andy McCall ↶ 173
    }
174
}
175
176
/// Every owner's backup (Admin › Backups), and the owners of repositories
177
/// that none covers, with how many each has.
178
pub async fn overview(pool: &Pool) -> sqlx::Result<(Vec<Overview>, Vec<(String, i64)>)> {
179
    let settings: Vec<Setting> = sqlx::query_as("SELECT * FROM backup_settings ORDER BY owner").fetch_all(pool).await?;
180
    let counts: Vec<(String, i64)> =
166f6e9b Andy McCall 181
        sqlx::query_as("SELECT owner, COUNT(*) FROM repositories WHERE kind = 'repo' GROUP BY owner ORDER BY owner")
182
            .fetch_all(pool)
183
            .await?;
1e8a6e8b Andy McCall ↶ 184
    let day_ago = db::now_ms() - 86_400_000;
185
    let mut out = Vec::new();
186
    for s in settings {
187
        let last = runs(pool, &s.owner, 1).await?.into_iter().next();
188
        let failed_day: i64 =
5d90e0e0 Andy McCall 189
            sqlx::query_scalar("SELECT COUNT(*) FROM backup_runs WHERE owner = $1 AND status = 'failed' AND started_ms >= $2")
1e8a6e8b Andy McCall ↶ 190
                .bind(&s.owner)
191
                .bind(day_ago)
192
                .fetch_one(pool)
193
                .await?;
d3b048b2 Andy McCall ↶ 194
        let repos = db::repos::list(pool).await?.iter().filter(|r| r.owner == s.owner && included(&s, r, false)).count() as i64;
1e8a6e8b Andy McCall ↶ 195
        out.push(Overview { setting: s, last, failed_day, repos });
196
    }
d3b048b2 Andy McCall ↶ 197
    let uncovered = counts.into_iter().filter(|(owner, _)| !out.iter().any(|o| o.setting.owner == *owner && o.repos > 0)).collect();
1e8a6e8b Andy McCall ↶ 198
    Ok((out, uncovered))
199
}
200
d7d18246 Andy McCall ↶ 201
// ---------------------------------------------------------------- where
202
203
/// Where backups are written: keys are `/`-separated paths.
204
pub trait Destination: Send + Sync {
205
    fn exists(&self, key: &str) -> Result<bool>;
206
    /// Write `bytes` at `key`, whole or not at all.
207
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()>;
208
    fn get(&self, key: &str) -> Result<Vec<u8>>;
209
    /// The names directly under `prefix` (files and "directories").
210
    fn list(&self, prefix: &str) -> Result<Vec<String>>;
211
    /// Remove `key` and everything under it.
212
    fn remove(&self, key: &str) -> Result<()>;
213
}
214
215
/// A directory on the hub's host.
216
pub struct Directory {
217
    pub root: PathBuf,
218
}
219
220
impl Directory {
221
    fn path(&self, key: &str) -> Result<PathBuf> {
222
        if key.split('/').any(|p| p == ".." || p == ".") || key.starts_with('/') {
223
            bail!("not a clean key: {key}");
224
        }
225
        Ok(self.root.join(key))
226
    }
227
}
228
229
impl Destination for Directory {
230
    fn exists(&self, key: &str) -> Result<bool> {
231
        Ok(self.path(key)?.exists())
232
    }
233
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()> {
234
        let p = self.path(key)?;
235
        std::fs::create_dir_all(p.parent().context("no parent")?)?;
236
        let tmp = p.with_extension(format!("part-{}", std::process::id()));
237
        std::fs::write(&tmp, bytes)?;
238
        std::fs::rename(&tmp, &p)?;
239
        Ok(())
240
    }
241
    fn get(&self, key: &str) -> Result<Vec<u8>> {
242
        let p = self.path(key)?;
243
        std::fs::read(&p).with_context(|| format!("read {}", p.display()))
244
    }
245
    fn list(&self, prefix: &str) -> Result<Vec<String>> {
246
        let p = self.path(prefix)?;
247
        let mut out: Vec<String> = match std::fs::read_dir(&p) {
248
            Ok(d) => d.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(),
249
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
250
            Err(e) => return Err(e.into()),
251
        };
252
        out.sort();
253
        Ok(out)
254
    }
255
    fn remove(&self, key: &str) -> Result<()> {
256
        let p = self.path(key)?;
257
        if p.is_dir() {
258
            std::fs::remove_dir_all(p)?;
259
        } else if p.exists() {
260
            std::fs::remove_file(p)?;
261
        }
262
        Ok(())
263
    }
264
}
265
35fea423 Andy McCall ↶ 266
/// A Cloud Storage bucket, reached keylessly (docs/backups.md §3, §6):
267
/// the hub mints a short token as `backup:OWNER`, Google's STS exchanges
268
/// it for an access token through the owner's workload identity
269
/// provider, and that writes the bucket. No key exists anywhere; the
270
/// access token lasts an hour and is fetched again before it runs out.
271
pub struct Gcs {
272
    bucket: String,
273
    /// Keys go under this, when set.
274
    prefix: String,
275
    storage: String,
276
    sts: String,
277
    /// The provider's resource name, `//iam.googleapis.com/projects/…`.
278
    provider: String,
279
    subject: String,
280
    app: Shared,
281
    client: reqwest::Client,
282
    rt: tokio::runtime::Handle,
283
    token: std::sync::Mutex<Option<(String, i64)>>,
284
}
285
286
impl Gcs {
287
    pub fn new(app: &Shared, s: &Setting) -> Gcs {
288
        Gcs {
289
            bucket: s.target.clone(),
290
            prefix: s.prefix.trim_matches('/').to_string(),
291
            storage: app.config.backups.storage_url.trim_end_matches('/').to_string(),
292
            sts: app.config.backups.sts_url.trim_end_matches('/').to_string(),
293
            provider: s.provider.clone(),
294
            subject: format!("backup:{}", s.owner),
295
            app: app.clone(),
296
            client: reqwest::Client::builder().timeout(std::time::Duration::from_secs(300)).build().unwrap_or_default(),
297
            rt: tokio::runtime::Handle::current(),
298
            token: std::sync::Mutex::new(None),
299
        }
300
    }
301
302
    fn name(&self, key: &str) -> String {
303
        if self.prefix.is_empty() {
304
            key.to_string()
305
        } else {
306
            format!("{}/{key}", self.prefix)
307
        }
308
    }
309
310
    /// An access token, exchanged for a fresh one of the hub's when the
311
    /// last is within five minutes of running out.
312
    fn access(&self) -> Result<String> {
313
        let now = db::now_ms();
314
        if let Some((t, until)) = self.token.lock().unwrap().as_ref() {
315
            if *until - now > 300_000 {
316
                return Ok(t.clone());
317
            }
318
        }
319
        let (token, expires_in) = self.rt.block_on(async {
320
            let issuer = self.app.oidc().await?;
321
            // Google's default audience for a provider: its name over https.
322
            let audience = format!("https:{}", self.provider);
323
            let jwt = issuer.mint_for(self.app.config.base_url(), &self.subject, &audience, db::now_ms(), 600);
324
            let res = self
325
                .client
326
                .post(format!("{}/v1/token", self.sts))
327
                .json(&serde_json::json!({
328
                    "grantType": "urn:ietf:params:oauth:grant-type:token-exchange",
329
                    "audience": self.provider,
330
                    "scope": "https://www.googleapis.com/auth/devstorage.read_write",
331
                    "requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
332
                    "subjectToken": jwt,
333
                    "subjectTokenType": "urn:ietf:params:oauth:token-type:jwt",
334
                }))
335
                .send()
336
                .await?;
337
            let status = res.status();
338
            let body: serde_json::Value = res.json().await.unwrap_or_default();
339
            if !status.is_success() {
340
                bail!(
341
                    "Google's token exchange refused {}: {} (check the provider's issuer is this hub's address and its attribute condition admits backup:)",
342
                    self.subject,
343
                    body["error_description"].as_str().or(body["error"].as_str()).unwrap_or("no reason given")
344
                );
345
            }
346
            let token = body["access_token"].as_str().context("the token exchange gave no access token")?.to_string();
347
            anyhow::Ok((token, body["expires_in"].as_i64().unwrap_or(3600)))
348
        })?;
349
        *self.token.lock().unwrap() = Some((token.clone(), now + expires_in * 1000));
350
        Ok(token)
351
    }
352
353
    fn object_url(&self, key: &str) -> Result<reqwest::Url> {
354
        let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
355
        u.path_segments_mut().map_err(|_| anyhow::anyhow!("bad storage URL"))?.push(&self.name(key));
356
        Ok(u)
357
    }
358
359
    fn refused(&self, what: &str, status: reqwest::StatusCode, body: &str) -> anyhow::Error {
360
        let hint = if status == reqwest::StatusCode::FORBIDDEN || status == reqwest::StatusCode::UNAUTHORIZED {
361
            format!(" (grant roles/storage.objectAdmin on gs://{} to the principal …/subject/{})", self.bucket, self.subject)
362
        } else {
363
            String::new()
364
        };
365
        anyhow::anyhow!("GCS {what}: {status}{hint}: {}", body.chars().take(200).collect::<String>())
366
    }
367
368
    /// Every object name under `full` (no delimiter), for removal.
369
    fn all_under(&self, full: &str) -> Result<Vec<String>> {
370
        let mut out = Vec::new();
371
        let mut page: Option<String> = None;
372
        loop {
373
            let token = self.access()?;
374
            let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
375
            u.query_pairs_mut().append_pair("prefix", full).append_pair("fields", "items(name),nextPageToken");
376
            if let Some(p) = &page {
377
                u.query_pairs_mut().append_pair("pageToken", p);
378
            }
379
            let body: serde_json::Value = self.rt.block_on(async {
380
                let res = self.client.get(u).bearer_auth(&token).send().await?;
381
                let status = res.status();
382
                let text = res.text().await?;
383
                if !status.is_success() {
384
                    return Err(self.refused("list", status, &text));
385
                }
386
                anyhow::Ok(serde_json::from_str(&text)?)
387
            })?;
388
            out.extend(body["items"].as_array().into_iter().flatten().filter_map(|i| i["name"].as_str().map(String::from)));
389
            match body["nextPageToken"].as_str() {
390
                Some(p) => page = Some(p.to_string()),
391
                None => return Ok(out),
392
            }
393
        }
394
    }
395
}
396
7b9f4570 Andy McCall ↶ 397
/// An S3 bucket, written keylessly (§3): the hub's own short-lived token
398
/// (`sub = backup:OWNER`, audience `sts.amazonaws.com`) is exchanged at AWS
399
/// STS (AssumeRoleWithWebIdentity) for an hour's credentials of the role
400
/// the owner names, and they sign each request (Signature Version 4).
401
pub struct S3 {
402
    bucket: String,
403
    prefix: String,
404
    region: String,
405
    /// The bucket's endpoint: scheme, host and any path before keys.
406
    base: reqwest::Url,
407
    sts: String,
408
    /// The IAM role's ARN.
409
    role: String,
410
    subject: String,
411
    app: Shared,
412
    client: reqwest::Client,
413
    rt: tokio::runtime::Handle,
414
    creds: std::sync::Mutex<Option<Creds>>,
415
}
416
417
#[derive(Clone)]
418
struct Creds {
419
    id: String,
420
    secret: String,
421
    token: String,
422
    until: i64,
423
}
424
425
/// The audience AWS expects of a web identity token.
426
pub const AWS_AUDIENCE: &str = "sts.amazonaws.com";
427
428
/// Percent-encoding as AWS signs it: everything but unreserved characters,
429
/// and `/` too unless `keep_slash`.
430
pub fn aws_encode(s: &str, keep_slash: bool) -> String {
431
    let mut out = String::new();
432
    for b in s.bytes() {
433
        match b {
434
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
435
            b'/' if keep_slash => out.push('/'),
436
            _ => out.push_str(&format!("%{b:02X}")),
437
        }
438
    }
439
    out
440
}
441
442
fn hmac(key: &[u8], data: &str) -> Vec<u8> {
443
    use hmac::Mac;
444
    let mut m = hmac::Hmac::<sha2::Sha256>::new_from_slice(key).expect("any key length");
445
    m.update(data.as_bytes());
446
    m.finalize().into_bytes().to_vec()
447
}
448
449
fn sha256_hex(data: &[u8]) -> String {
450
    use sha2::Digest;
451
    hex::encode(sha2::Sha256::digest(data))
452
}
453
454
/// AWS Signature Version 4: the `Authorization` header for one request.
455
/// `uri` is the path as encoded on the wire, `query` the decoded pairs,
456
/// `headers` the signed ones (any case), `payload` the body's SHA-256 in
457
/// hex, `amz_date` as `20130524T000000Z`.
458
#[allow(clippy::too_many_arguments)]
459
pub fn sigv4(
460
    method: &str,
461
    uri: &str,
462
    query: &[(String, String)],
463
    headers: &[(String, String)],
464
    payload: &str,
465
    (id, secret): (&str, &str),
466
    region: &str,
467
    service: &str,
468
    amz_date: &str,
469
) -> String {
470
    let mut q: Vec<(String, String)> = query.iter().map(|(k, v)| (aws_encode(k, false), aws_encode(v, false))).collect();
471
    q.sort();
472
    let query = q.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&");
473
    let mut h: Vec<(String, String)> = headers.iter().map(|(k, v)| (k.to_ascii_lowercase(), v.trim().to_string())).collect();
474
    h.sort();
475
    let canonical_headers: String = h.iter().map(|(k, v)| format!("{k}:{v}\n")).collect();
476
    let signed = h.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(";");
477
    let request = format!("{method}\n{uri}\n{query}\n{canonical_headers}\n{signed}\n{payload}");
478
    let date = &amz_date[..8];
479
    let scope = format!("{date}/{region}/{service}/aws4_request");
480
    let to_sign = format!("AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}", sha256_hex(request.as_bytes()));
481
    let key = hmac(&hmac(&hmac(&hmac(format!("AWS4{secret}").as_bytes(), date), region), service), "aws4_request");
482
    let signature = hex::encode(hmac(&key, &to_sign));
483
    format!("AWS4-HMAC-SHA256 Credential={id}/{scope}, SignedHeaders={signed}, Signature={signature}")
484
}
485
486
/// The text of the first `<tag>` in `xml`, unescaped.
487
fn xml_text(xml: &str, tag: &str) -> Option<String> {
488
    xml_blocks(xml, tag).into_iter().next().map(xml_unescape)
489
}
490
491
/// The inside of every `<tag>…</tag>` in `xml`.
492
fn xml_blocks<'a>(xml: &'a str, tag: &str) -> Vec<&'a str> {
493
    let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
494
    let mut out = Vec::new();
495
    let mut rest = xml;
496
    while let Some(i) = rest.find(&open) {
497
        let after = &rest[i + open.len()..];
498
        let Some(j) = after.find(&close) else { break };
499
        out.push(&after[..j]);
500
        rest = &after[j + close.len()..];
501
    }
502
    out
503
}
504
505
fn xml_unescape(s: &str) -> String {
506
    s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
507
}
508
509
fn amz_date(ms: i64) -> String {
510
    let t = time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
511
    format!("{:04}{:02}{:02}T{:02}{:02}{:02}Z", t.year(), u8::from(t.month()), t.day(), t.hour(), t.minute(), t.second())
512
}
513
514
impl S3 {
515
    pub fn new(app: &Shared, s: &Setting) -> S3 {
516
        let url = app.config.backups.s3_url.replace("{bucket}", &s.target).replace("{region}", &s.region);
517
        S3 {
518
            bucket: s.target.clone(),
519
            prefix: s.prefix.trim_matches('/').to_string(),
520
            region: s.region.clone(),
521
            base: reqwest::Url::parse(url.trim_end_matches('/')).unwrap_or_else(|_| reqwest::Url::parse("https://invalid.").unwrap()),
522
            sts: app.config.backups.aws_sts_url.trim_end_matches('/').to_string(),
523
            role: s.provider.clone(),
524
            subject: format!("backup:{}", s.owner),
525
            app: app.clone(),
526
            client: reqwest::Client::builder().timeout(std::time::Duration::from_secs(300)).build().unwrap_or_default(),
527
            rt: tokio::runtime::Handle::current(),
528
            creds: std::sync::Mutex::new(None),
529
        }
530
    }
531
532
    fn name(&self, key: &str) -> String {
533
        if self.prefix.is_empty() {
534
            key.to_string()
535
        } else {
536
            format!("{}/{key}", self.prefix)
537
        }
538
    }
539
540
    /// Credentials of the owner's role, exchanged again when the last are
541
    /// within five minutes of running out.
542
    fn creds(&self) -> Result<Creds> {
543
        let now = db::now_ms();
544
        if let Some(c) = self.creds.lock().unwrap().as_ref() {
545
            if c.until - now > 300_000 {
546
                return Ok(c.clone());
547
            }
548
        }
549
        let session: String = format!("oxygenhub-{}", self.subject.trim_start_matches("backup:"))
550
            .chars()
551
            .filter(|c| c.is_ascii_alphanumeric() || "=,.@-_".contains(*c))
552
            .take(64)
553
            .collect();
554
        let c = self.rt.block_on(async {
555
            let issuer = self.app.oidc().await?;
556
            let jwt = issuer.mint_for(self.app.config.base_url(), &self.subject, AWS_AUDIENCE, db::now_ms(), 600);
557
            let res = self
558
                .client
559
                .post(format!("{}/", self.sts))
560
                .form(&[
561
                    ("Action", "AssumeRoleWithWebIdentity"),
562
                    ("Version", "2011-06-15"),
563
                    ("RoleArn", self.role.as_str()),
564
                    ("RoleSessionName", session.as_str()),
565
                    ("WebIdentityToken", jwt.as_str()),
566
                    ("DurationSeconds", "3600"),
567
                ])
568
                .send()
569
                .await?;
570
            let status = res.status();
571
            let text = res.text().await.unwrap_or_default();
572
            if !status.is_success() {
573
                bail!(
574
                    "AWS STS refused {} for {}: {} (check the role's trust policy: this hub's address as its OIDC provider, audience {AWS_AUDIENCE}, and sub {})",
575
                    self.subject,
576
                    self.role,
577
                    xml_text(&text, "Message").unwrap_or_else(|| status.to_string()),
578
                    self.subject
579
                );
580
            }
581
            let get = |t: &str| xml_text(&text, t).with_context(|| format!("AWS STS gave no {t}"));
582
            anyhow::Ok(Creds { id: get("AccessKeyId")?, secret: get("SecretAccessKey")?, token: get("SessionToken")?, until: now + 3_600_000 })
583
        })?;
584
        *self.creds.lock().unwrap() = Some(c.clone());
585
        Ok(c)
586
    }
587
588
    /// One signed request: `key` is an object's (none for the bucket).
589
    fn send(
590
        &self,
591
        method: reqwest::Method,
592
        key: Option<&str>,
593
        query: &[(String, String)],
594
        body: Vec<u8>,
595
    ) -> Result<(reqwest::StatusCode, Vec<u8>)> {
596
        let c = self.creds()?;
597
        let base_path = self.base.path().trim_end_matches('/');
598
        let uri = match key {
599
            Some(k) => format!("{base_path}/{}", aws_encode(&self.name(k), true)),
600
            None => format!("{base_path}/"),
601
        };
602
        let host = match self.base.port() {
603
            Some(p) => format!("{}:{p}", self.base.host_str().unwrap_or_default()),
604
            None => self.base.host_str().unwrap_or_default().to_string(),
605
        };
606
        let payload = sha256_hex(&body);
607
        let date = amz_date(db::now_ms());
608
        let headers = vec![
609
            ("host".to_string(), host.clone()),
610
            ("x-amz-content-sha256".to_string(), payload.clone()),
611
            ("x-amz-date".to_string(), date.clone()),
612
            ("x-amz-security-token".to_string(), c.token.clone()),
613
        ];
614
        let auth = sigv4(method.as_str(), &uri, query, &headers, &payload, (&c.id, &c.secret), &self.region, "s3", &date);
615
        let mut q: Vec<(String, String)> = query.iter().map(|(k, v)| (aws_encode(k, false), aws_encode(v, false))).collect();
616
        q.sort();
617
        let qs = q.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&");
618
        let url = format!("{}://{host}{uri}{}{qs}", self.base.scheme(), if qs.is_empty() { "" } else { "?" });
0cd11874 Andy McCall ↶ 619
        let method_has_body = method == reqwest::Method::PUT;
7b9f4570 Andy McCall ↶ 620
        self.rt.block_on(async {
621
            let mut req = self
622
                .client
623
                .request(method, &url)
624
                .header("authorization", auth)
625
                .header("x-amz-content-sha256", &payload)
626
                .header("x-amz-date", &date)
627
                .header("x-amz-security-token", &c.token);
628
            if !body.is_empty() {
0cd11874 Andy McCall ↶ 629
                req = req.header("content-type", "application/octet-stream");
7b9f4570 Andy McCall ↶ 630
            }
0cd11874 Andy McCall ↶ 631
            // Always the length, an empty body's too: S3 and GCS refuse
632
            // an upload without one (411 Length Required).
633
            if method_has_body {
634
                req = req.header("content-length", body.len().to_string()).body(body);
635
            }
7b9f4570 Andy McCall ↶ 636
            let res = req.send().await?;
637
            let status = res.status();
638
            anyhow::Ok((status, res.bytes().await?.to_vec()))
639
        })
640
    }
641
642
    fn refused(&self, what: &str, status: reqwest::StatusCode, body: &[u8]) -> anyhow::Error {
643
        let text = String::from_utf8_lossy(body);
644
        let hint = if status == reqwest::StatusCode::FORBIDDEN {
645
            format!(" (the role {} needs s3:GetObject, s3:PutObject, s3:DeleteObject and s3:ListBucket on {})", self.role, self.bucket)
646
        } else {
647
            String::new()
648
        };
649
        anyhow::anyhow!("S3 {what}: {status}{hint}: {}", xml_text(&text, "Message").unwrap_or_else(|| text.chars().take(200).collect()))
650
    }
651
652
    /// The keys under `full` (`delimited`: and the next level's prefixes).
653
    fn listing(&self, full: &str, delimited: bool) -> Result<(Vec<String>, Vec<String>)> {
654
        let (mut keys, mut prefixes) = (Vec::new(), Vec::new());
655
        let mut token: Option<String> = None;
656
        loop {
657
            let mut q = vec![("list-type".to_string(), "2".to_string()), ("prefix".to_string(), full.to_string())];
658
            if delimited {
659
                q.push(("delimiter".to_string(), "/".to_string()));
660
            }
661
            if let Some(t) = &token {
662
                q.push(("continuation-token".to_string(), t.clone()));
663
            }
664
            let (status, body) = self.send(reqwest::Method::GET, None, &q, Vec::new())?;
665
            if !status.is_success() {
666
                return Err(self.refused("list", status, &body));
667
            }
668
            let text = String::from_utf8_lossy(&body).into_owned();
669
            for c in xml_blocks(&text, "Contents") {
670
                keys.extend(xml_text(c, "Key"));
671
            }
672
            for c in xml_blocks(&text, "CommonPrefixes") {
673
                prefixes.extend(xml_text(c, "Prefix"));
674
            }
675
            match (xml_text(&text, "IsTruncated").as_deref(), xml_text(&text, "NextContinuationToken")) {
676
                (Some("true"), Some(t)) => token = Some(t),
677
                _ => return Ok((keys, prefixes)),
678
            }
679
        }
680
    }
681
}
682
683
impl Destination for S3 {
684
    fn exists(&self, key: &str) -> Result<bool> {
685
        let (status, body) = self.send(reqwest::Method::HEAD, Some(key), &[], Vec::new())?;
686
        match status {
687
            s if s.is_success() => Ok(true),
688
            reqwest::StatusCode::NOT_FOUND => Ok(false),
689
            s => Err(self.refused("read", s, &body)),
690
        }
691
    }
692
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()> {
693
        let (status, body) = self.send(reqwest::Method::PUT, Some(key), &[], bytes.to_vec())?;
694
        if !status.is_success() {
695
            return Err(self.refused("write", status, &body));
696
        }
697
        Ok(())
698
    }
699
    fn get(&self, key: &str) -> Result<Vec<u8>> {
700
        let (status, body) = self.send(reqwest::Method::GET, Some(key), &[], Vec::new())?;
701
        if !status.is_success() {
702
            return Err(self.refused(&format!("read {key}"), status, &body));
703
        }
704
        Ok(body)
705
    }
706
    fn list(&self, prefix: &str) -> Result<Vec<String>> {
707
        let full = format!("{}/", self.name(prefix.trim_end_matches('/')));
708
        let (keys, prefixes) = self.listing(&full, true)?;
709
        let mut out: std::collections::BTreeSet<String> = keys.iter().map(|k| k.trim_start_matches(&full).to_string()).collect();
710
        out.extend(prefixes.iter().map(|p| p.trim_start_matches(&full).trim_end_matches('/').to_string()));
711
        Ok(out.into_iter().filter(|n| !n.is_empty()).collect())
712
    }
713
    fn remove(&self, key: &str) -> Result<()> {
714
        let full = self.name(key);
715
        let (mut keys, _) = self.listing(&format!("{full}/"), false)?;
716
        keys.push(full);
717
        for k in keys {
718
            let rel = if self.prefix.is_empty() { k.clone() } else { k.trim_start_matches(&format!("{}/", self.prefix)).to_string() };
719
            let (status, body) = self.send(reqwest::Method::DELETE, Some(&rel), &[], Vec::new())?;
720
            if !status.is_success() && status != reqwest::StatusCode::NOT_FOUND {
721
                return Err(self.refused("remove", status, &body));
722
            }
723
        }
724
        Ok(())
725
    }
726
}
727
35fea423 Andy McCall ↶ 728
impl Destination for Gcs {
729
    fn exists(&self, key: &str) -> Result<bool> {
730
        let token = self.access()?;
731
        let mut u = self.object_url(key)?;
732
        u.query_pairs_mut().append_pair("fields", "name");
733
        self.rt.block_on(async {
734
            let res = self.client.get(u).bearer_auth(&token).send().await?;
735
            match res.status() {
736
                s if s.is_success() => Ok(true),
737
                reqwest::StatusCode::NOT_FOUND => Ok(false),
738
                s => Err(self.refused("read", s, &res.text().await.unwrap_or_default())),
739
            }
740
        })
741
    }
742
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()> {
743
        let token = self.access()?;
744
        let mut u = reqwest::Url::parse(&format!("{}/upload/storage/v1/b/{}/o", self.storage, self.bucket))?;
745
        u.query_pairs_mut().append_pair("uploadType", "media").append_pair("name", &self.name(key));
746
        let body = bytes.to_vec();
747
        self.rt.block_on(async {
0cd11874 Andy McCall ↶ 748
            // The length always, an empty object's too: Google refuses an
749
            // upload without one (411 Length Required).
750
            let res = self
751
                .client
752
                .post(u)
753
                .bearer_auth(&token)
754
                .header("content-type", "application/octet-stream")
755
                .header("content-length", body.len().to_string())
756
                .body(body)
757
                .send()
758
                .await?;
35fea423 Andy McCall ↶ 759
            let status = res.status();
760
            if !status.is_success() {
761
                return Err(self.refused("write", status, &res.text().await.unwrap_or_default()));
762
            }
763
            Ok(())
764
        })
765
    }
766
    fn get(&self, key: &str) -> Result<Vec<u8>> {
767
        let token = self.access()?;
768
        let mut u = self.object_url(key)?;
769
        u.query_pairs_mut().append_pair("alt", "media");
770
        self.rt.block_on(async {
771
            let res = self.client.get(u).bearer_auth(&token).send().await?;
772
            let status = res.status();
773
            if !status.is_success() {
774
                return Err(self.refused(&format!("read {key}"), status, &res.text().await.unwrap_or_default()));
775
            }
776
            Ok(res.bytes().await?.to_vec())
777
        })
778
    }
779
    fn list(&self, prefix: &str) -> Result<Vec<String>> {
780
        let full = format!("{}/", self.name(prefix.trim_end_matches('/')));
781
        let mut out = std::collections::BTreeSet::new();
782
        let mut page: Option<String> = None;
783
        loop {
784
            let token = self.access()?;
785
            let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
786
            u.query_pairs_mut()
787
                .append_pair("prefix", &full)
788
                .append_pair("delimiter", "/")
789
                .append_pair("fields", "items(name),prefixes,nextPageToken");
790
            if let Some(p) = &page {
791
                u.query_pairs_mut().append_pair("pageToken", p);
792
            }
793
            let body: serde_json::Value = self.rt.block_on(async {
794
                let res = self.client.get(u).bearer_auth(&token).send().await?;
795
                let status = res.status();
796
                let text = res.text().await?;
797
                if !status.is_success() {
798
                    return Err(self.refused("list", status, &text));
799
                }
800
                anyhow::Ok(serde_json::from_str(&text)?)
801
            })?;
802
            for n in body["items"].as_array().into_iter().flatten().filter_map(|i| i["name"].as_str()) {
803
                out.insert(n.trim_start_matches(&full).to_string());
804
            }
805
            for p in body["prefixes"].as_array().into_iter().flatten().filter_map(|p| p.as_str()) {
806
                out.insert(p.trim_start_matches(&full).trim_end_matches('/').to_string());
807
            }
808
            match body["nextPageToken"].as_str() {
809
                Some(p) => page = Some(p.to_string()),
810
                None => return Ok(out.into_iter().filter(|n| !n.is_empty()).collect()),
811
            }
812
        }
813
    }
814
    fn remove(&self, key: &str) -> Result<()> {
815
        let mut names = self.all_under(&format!("{}/", self.name(key)))?;
816
        names.push(self.name(key));
817
        for n in names {
818
            let token = self.access()?;
819
            let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
820
            u.path_segments_mut().map_err(|_| anyhow::anyhow!("bad storage URL"))?.push(&n);
821
            self.rt.block_on(async {
822
                let res = self.client.delete(u).bearer_auth(&token).send().await?;
823
                match res.status() {
824
                    s if s.is_success() || s == reqwest::StatusCode::NOT_FOUND => Ok(()),
825
                    s => Err(self.refused("delete", s, &res.text().await.unwrap_or_default())),
826
                }
827
            })?;
828
        }
829
        Ok(())
830
    }
831
}
832
833
/// Check a destination end to end: write a probe, read it back, remove it.
834
pub fn probe(dest: &dyn Destination) -> Result<()> {
835
    let marker = format!("probe {}", db::now_ms());
836
    dest.put(".oxyhub-probe", marker.as_bytes())?;
837
    if dest.get(".oxyhub-probe")? != marker.as_bytes() {
838
        bail!("the probe read back differently");
839
    }
840
    dest.remove(".oxyhub-probe")
841
}
842
d7d18246 Andy McCall ↶ 843
/// The owner's destination, from its setting and the site's rules.
844
pub fn destination(app: &Shared, s: &Setting) -> Result<Box<dyn Destination>> {
845
    match s.destination.as_str() {
846
        "dir" => {
847
            let allowed = &app.config.backups.directories;
848
            let target = PathBuf::from(&s.target);
849
            if !allowed.contains(&target) {
850
                bail!("{} is not a backup directory this hub allows (hub.toml [backups] directories)", s.target);
851
            }
852
            let mut root = target.join(&s.owner);
853
            if !s.prefix.is_empty() {
854
                root = root.join(s.prefix.trim_matches('/'));
855
            }
856
            Ok(Box::new(Directory { root }))
35fea423 Andy McCall ↶ 857
        }
858
        "gcs" => {
859
            if s.target.is_empty() || s.provider.is_empty() {
860
                bail!("a GCS destination needs its bucket and its workload identity provider");
861
            }
862
            Ok(Box::new(Gcs::new(app, s)))
7b9f4570 Andy McCall ↶ 863
        }
864
        "s3" => {
865
            if s.target.is_empty() || s.provider.is_empty() || s.region.is_empty() {
866
                bail!("an S3 destination needs its bucket, its region and the IAM role the hub assumes");
867
            }
868
            Ok(Box::new(S3::new(app, s)))
d7d18246 Andy McCall ↶ 869
        }
870
        other => bail!("unknown destination {other:?}"),
871
    }
872
}
873
874
// ---------------------------------------------------------------- what
875
876
/// One file of a repository's store, in a manifest.
877
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
878
pub struct File {
879
    pub path: String,
880
    pub size: u64,
881
    /// Its modification time in nanoseconds: unchanged size and time mean
882
    /// unchanged content, so it is not hashed again.
883
    pub mtime: i128,
884
    pub hash: String,
885
}
886
887
/// A repository at one run.
888
#[derive(Clone, Debug, Serialize, Deserialize)]
889
pub struct Manifest {
890
    pub owner: String,
891
    pub name: String,
892
    /// `repos` or `wikis`.
893
    pub kind: String,
894
    pub files: Vec<File>,
895
}
896
897
fn blob_key(hash: &str) -> String {
898
    format!("blobs/{}/{hash}", &hash[..2])
899
}
900
901
/// The large files that never change once written come first.
902
fn immutable(path: &str) -> bool {
903
    path.starts_with(".oxy/objects/") && (path.contains("/pack-") || path.contains("/loose/"))
904
}
905
906
#[derive(Default)]
907
struct Sent {
908
    files: i64,
909
    sent: i64,
910
    bytes: i64,
911
}
912
913
/// Walk `dir`, sending each file the destination lacks; `known` says which
914
/// paths are unchanged since the last run (and their hashes).
915
fn copy_dir(dest: &dyn Destination, dir: &Path, known: &HashMap<String, File>, only_immutable: bool, sent: &mut Sent) -> Result<Vec<File>> {
916
    let mut out = Vec::new();
917
    let mut stack = vec![dir.to_path_buf()];
918
    while let Some(d) = stack.pop() {
919
        let entries = match std::fs::read_dir(&d) {
920
            Ok(e) => e,
921
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
922
            Err(e) => return Err(e.into()),
923
        };
924
        for e in entries.flatten() {
925
            let p = e.path();
926
            let ft = e.file_type()?;
927
            if ft.is_dir() {
928
                stack.push(p);
929
                continue;
930
            }
931
            if !ft.is_file() {
932
                continue;
933
            }
934
            let rel = p.strip_prefix(dir).unwrap_or(&p).to_string_lossy().replace('\\', "/");
935
            if only_immutable && !immutable(&rel) {
936
                continue;
937
            }
938
            // A file packed away while the walk ran is simply gone.
939
            let Ok(md) = std::fs::metadata(&p) else { continue };
940
            let mtime =
941
                md.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos() as i128).unwrap_or(0);
942
            let size = md.len();
943
            sent.files += 1;
944
            if let Some(k) = known.get(&rel).filter(|k| k.size == size && k.mtime == mtime) {
945
                out.push(k.clone());
946
                continue;
947
            }
948
            let Ok(bytes) = std::fs::read(&p) else { continue };
949
            let hash = blake3::hash(&bytes).to_hex().to_string();
950
            let key = blob_key(&hash);
951
            if !dest.exists(&key)? {
952
                dest.put(&key, &bytes)?;
953
                sent.sent += 1;
954
                sent.bytes += bytes.len() as i64;
955
            }
956
            out.push(File { path: rel, size, mtime, hash });
957
        }
958
    }
959
    out.sort_by(|a, b| a.path.cmp(&b.path));
960
    Ok(out)
961
}
962
963
// ---------------------------------------------------------------- records
964
965
/// Tables and columns never written: secrets, credentials, sessions.
966
fn private_table(t: &str) -> bool {
967
    ["secret", "token", "session", "password", "totp", "recovery", "sqlx"].iter().any(|w| t.contains(w))
968
}
969
970
fn private_column(c: &str) -> bool {
971
    ["secret", "token", "password", "salt", "totp", "sealed", "hash_key"].iter().any(|w| c.contains(w))
972
}
973
974
async fn tables(pool: &Pool) -> Result<Vec<String>> {
3b1bc27f Andy McCall 975
    let mut t = catalog::tables(pool).await?;
d7d18246 Andy McCall ↶ 976
    t.retain(|t| !private_table(t));
977
    t.sort();
978
    Ok(t)
979
}
980
981
async fn columns(pool: &Pool, table: &str) -> Result<Vec<String>> {
3b1bc27f Andy McCall 982
    Ok(table_cols(pool, table).await?.into_iter().map(|c| c.name).collect())
d7d18246 Andy McCall ↶ 983
}
984
985
/// The rows of `table` matching `cond`, as a JSON array, private columns
3b1bc27f Andy McCall 986
/// left out, blobs as hex and flags as 0 or 1, whichever engine wrote them,
987
/// so a run from either restores into either.
d7d18246 Andy McCall ↶ 988
async fn rows(pool: &Pool, table: &str, cond: &str) -> Result<serde_json::Value> {
3b1bc27f Andy McCall 989
    let cols: Vec<Col> = table_cols(pool, table).await?.into_iter().filter(|c| !private_column(&c.name)).collect();
990
    if cols.is_empty() {
d7d18246 Andy McCall ↶ 991
        return Ok(serde_json::json!([]));
992
    }
3b1bc27f Andy McCall 993
    let text: String = sqlx::query_scalar(&catalog::rows_sql(table, &cols, cond)).fetch_one(pool).await?;
d7d18246 Andy McCall ↶ 994
    Ok(serde_json::from_str(&text)?)
995
}
996
3b1bc27f Andy McCall 997
/// What backups ask of the database's own catalog, per engine. Column
998
/// types are given in SQLite's words (INTEGER, TEXT, BLOB, REAL) plus
999
/// BOOLEAN, which only Postgres has.
1000
#[cfg(not(feature = "postgres"))]
1001
mod catalog {
1002
    use super::{Col, Pool, Result};
1003
1004
    pub async fn tables(pool: &Pool) -> Result<Vec<String>> {
1005
        Ok(sqlx::query_scalar("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").fetch_all(pool).await?)
1006
    }
1007
1008
    pub async fn cols(pool: &Pool, table: &str) -> Result<Vec<Col>> {
1009
        let rows: Vec<(String, String, i64, Option<String>, i64)> =
1010
            sqlx::query_as(&format!("SELECT name, type, \"notnull\", dflt_value, pk FROM pragma_table_info('{table}')"))
1011
                .fetch_all(pool)
1012
                .await?;
1013
        Ok(rows.into_iter().map(|(name, ty, notnull, default, pk)| Col { name, ty, notnull: notnull != 0, default, pk }).collect())
1014
    }
1015
1016
    /// `(parent table, column, parent column)` for each reference.
1017
    pub async fn fks(pool: &Pool, table: &str) -> Result<Vec<(String, String, String)>> {
1018
        Ok(sqlx::query_as(&format!("SELECT \"table\", \"from\", \"to\" FROM pragma_foreign_key_list('{table}')")).fetch_all(pool).await?)
1019
    }
1020
1021
    pub fn rows_sql(table: &str, cols: &[Col], cond: &str) -> String {
1022
        let fields: Vec<String> =
1023
            cols.iter().map(|c| format!("'{0}', CASE WHEN typeof(\"{0}\") = 'blob' THEN hex(\"{0}\") ELSE \"{0}\" END", c.name)).collect();
1024
        format!("SELECT json_group_array(json_object({})) FROM \"{table}\" WHERE {cond}", fields.join(", "))
1025
    }
1026
1027
    /// How a restored row goes in when its key is taken: `INSERT …` then this.
1028
    pub fn insert(verb: super::Verb, _cols: &[String]) -> (&'static str, String) {
1029
        match verb {
1030
            super::Verb::Replace => ("INSERT OR REPLACE", String::new()),
1031
            super::Verb::New => ("INSERT", String::new()),
1032
            super::Verb::Ignore => ("INSERT OR IGNORE", String::new()),
1033
        }
1034
    }
1035
}
1036
1037
#[cfg(feature = "postgres")]
1038
mod catalog {
1039
    use super::{Col, Pool, Result};
1040
1041
    pub async fn tables(pool: &Pool) -> Result<Vec<String>> {
1042
        Ok(sqlx::query_scalar(
1043
            "SELECT CAST(relname AS TEXT) FROM pg_class WHERE relkind = 'r' AND relnamespace = CAST(current_schema() AS regnamespace)",
1044
        )
1045
        .fetch_all(pool)
1046
        .await?)
1047
    }
1048
1049
    /// Generated columns (the search index's) are left out: they are made,
1050
    /// never restored.
1051
    pub async fn cols(pool: &Pool, table: &str) -> Result<Vec<Col>> {
1052
        // pg_catalog, not information_schema: many times faster.
1053
        let rows: Vec<(String, String, bool, Option<String>, i64)> = sqlx::query_as(
1054
            "SELECT CAST(a.attname AS TEXT), format_type(a.atttypid, a.atttypmod), a.attnotnull, pg_get_expr(d.adbin, d.adrelid), \
1055
               CAST(COALESCE((SELECT array_position(k.conkey, a.attnum) FROM pg_constraint k WHERE k.conrelid = t.oid AND k.contype = 'p'), 0) AS BIGINT) \
1056
             FROM pg_attribute a JOIN pg_class t ON t.oid = a.attrelid \
1057
             LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
1058
             WHERE t.relname = $1 AND t.relnamespace = CAST(current_schema() AS regnamespace) \
1059
               AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = '' ORDER BY a.attnum",
1060
        )
1061
        .bind(table)
1062
        .fetch_all(pool)
1063
        .await?;
1064
        Ok(rows
1065
            .into_iter()
1066
            .map(|(name, ty, notnull, default, pk)| {
1067
                let ty = match ty.as_str() {
1068
                    "bigint" | "integer" | "smallint" => "INTEGER",
1069
                    "bytea" => "BLOB",
1070
                    "boolean" => "BOOLEAN",
1071
                    "double precision" | "real" => "REAL",
1072
                    _ => "TEXT",
1073
                };
1074
                // An identity column's default is the sequence, as SQLite's
1075
                // rowid: none to give.
1076
                let default = default.filter(|d| !d.starts_with("nextval("));
1077
                Col { name, ty: ty.to_string(), notnull, default, pk }
1078
            })
1079
            .collect())
1080
    }
1081
1082
    /// `(parent table, column, parent column)` for each reference.
1083
    pub async fn fks(pool: &Pool, table: &str) -> Result<Vec<(String, String, String)>> {
1084
        Ok(sqlx::query_as(
1085
            "SELECT CAST(p.relname AS TEXT), CAST(a.attname AS TEXT), CAST(pa.attname AS TEXT) FROM pg_constraint k \
1086
             JOIN pg_class t ON t.oid = k.conrelid JOIN pg_class p ON p.oid = k.confrelid \
1087
             JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = k.conkey[1] \
1088
             JOIN pg_attribute pa ON pa.attrelid = k.confrelid AND pa.attnum = k.confkey[1] \
1089
             WHERE k.contype = 'f' AND t.relname = $1 AND t.relnamespace = CAST(current_schema() AS regnamespace)",
1090
        )
1091
        .bind(table)
1092
        .fetch_all(pool)
1093
        .await?)
1094
    }
1095
1096
    pub fn rows_sql(table: &str, cols: &[Col], cond: &str) -> String {
1097
        let fields: Vec<String> = cols
1098
            .iter()
1099
            .map(|c| match c.ty.as_str() {
1100
                "BLOB" => format!("upper(encode(\"{0}\", 'hex')) AS \"{0}\"", c.name),
1101
                "BOOLEAN" => format!("CASE WHEN \"{0}\" THEN 1 ELSE 0 END AS \"{0}\"", c.name),
1102
                _ => format!("\"{0}\"", c.name),
1103
            })
1104
            .collect();
1105
        format!("SELECT CAST(COALESCE(json_agg(r), '[]') AS TEXT) FROM (SELECT {} FROM \"{table}\" WHERE {cond}) r", fields.join(", "))
1106
    }
1107
1108
    /// How a restored row goes in when its key is taken: `INSERT …` then this.
1109
    pub fn insert(verb: super::Verb, cols: &[String]) -> (&'static str, String) {
1110
        match verb {
1111
            super::Verb::Replace => {
1112
                let set: Vec<String> = cols.iter().filter(|c| *c != "repo_id").map(|c| format!("\"{c}\" = excluded.\"{c}\"")).collect();
1113
                let tail = if set.is_empty() {
1114
                    " ON CONFLICT (repo_id) DO NOTHING".to_string()
1115
                } else {
1116
                    format!(" ON CONFLICT (repo_id) DO UPDATE SET {}", set.join(", "))
1117
                };
1118
                ("INSERT", tail)
1119
            }
1120
            super::Verb::New => ("INSERT", String::new()),
1121
            super::Verb::Ignore => ("INSERT", " ON CONFLICT DO NOTHING".to_string()),
1122
        }
1123
    }
1124
}
1125
1126
/// How restored rows meet the rows already there.
1127
#[derive(Clone, Copy)]
1128
enum Verb {
1129
    /// One row per repository: the restored one wins.
1130
    Replace,
1131
    /// A row with an id of its own, given a new one.
1132
    New,
1133
    /// Kept as it is when already there.
1134
    Ignore,
1135
}
1136
d7d18246 Andy McCall ↶ 1137
/// Every row about something: the tables with column `key` equal to `id`,
1138
/// then, three levels deep, the tables whose foreign keys point at rows
1139
/// already taken (an issue's comments, a proposal's reviews and their
1140
/// threads).
1141
async fn records(pool: &Pool, key: &str, id: i64) -> Result<serde_json::Value> {
1142
    let all = tables(pool).await?;
1143
    let mut conds: Vec<(String, String)> = Vec::new();
1144
    for t in &all {
1145
        if columns(pool, t).await?.iter().any(|c| c == key) {
1146
            conds.push((t.clone(), format!("\"{key}\" = {id}")));
1147
        }
1148
    }
1149
    for _ in 0..3 {
1150
        let mut more = Vec::new();
1151
        for t in &all {
1152
            if conds.iter().any(|(c, _)| c == t) || more.iter().any(|(c, _): &(String, String)| c == t) {
1153
                continue;
1154
            }
3b1bc27f Andy McCall 1155
            let fks = catalog::fks(pool, t).await?;
d7d18246 Andy McCall ↶ 1156
            if let Some((parent, from, to, pcond)) = fks
1157
                .iter()
1158
                .find_map(|(p, f, to)| conds.iter().find(|(c, _)| c == p).map(|(_, pc)| (p.clone(), f.clone(), to.clone(), pc.clone())))
1159
            {
1160
                more.push((t.clone(), format!("\"{from}\" IN (SELECT \"{to}\" FROM \"{parent}\" WHERE {pcond})")));
1161
            }
1162
        }
1163
        if more.is_empty() {
1164
            break;
1165
        }
1166
        conds.extend(more);
1167
    }
1168
    let mut out = serde_json::Map::new();
1169
    for (t, cond) in conds {
1170
        let r = rows(pool, &t, &cond).await?;
1171
        if r.as_array().is_some_and(|a| !a.is_empty()) {
1172
            out.insert(t, r);
1173
        }
1174
    }
1175
    Ok(serde_json::Value::Object(out))
1176
}
1177
5ef6cf72 Andy McCall ↶ 1178
/// The key of a run's records naming the accounts, teams and organisations
1179
/// their rows point at, by id: `{"accounts": {"7": "andy"}, …}`.
1180
const NAMES: &str = "_names";
1181
1182
/// Tables a restore leaves out: the search index (rebuilt from what is
1183
/// restored), and what is passing or personal rather than the
1184
/// repository's: inboxes, webhook deliveries, runners' declines.
1185
const NOT_RESTORED: [&str; 5] = ["search", "notifications", "deliveries", "flow_declines", NAMES];
1186
1187
async fn fk_list(pool: &Pool, table: &str) -> Result<Vec<(String, String, String)>> {
3b1bc27f Andy McCall 1188
    catalog::fks(pool, table).await
5ef6cf72 Andy McCall ↶ 1189
}
1190
1191
/// The names behind the account, team and organisation ids that `rec`'s
1192
/// rows point at, so a restore on another hub finds them again by name.
1193
async fn names_of(pool: &Pool, rec: &serde_json::Value) -> Result<serde_json::Value> {
1194
    let mut ids: HashMap<String, std::collections::BTreeSet<i64>> = HashMap::new();
1195
    for (table, rows) in rec.as_object().into_iter().flatten() {
1196
        let Some(rows) = rows.as_array() else { continue };
1197
        for (parent, from, _) in fk_list(pool, table).await? {
1198
            if ["accounts", "teams", "organisations"].contains(&parent.as_str()) {
1199
                ids.entry(parent).or_default().extend(rows.iter().filter_map(|r| r[&from].as_i64()));
1200
            }
1201
        }
1202
    }
1203
    let mut out = serde_json::Map::new();
1204
    for (kind, sql) in [
5d90e0e0 Andy McCall 1205
        ("accounts", "SELECT id, username FROM accounts WHERE id = $1"),
1206
        ("organisations", "SELECT id, name FROM organisations WHERE id = $1"),
1207
        ("teams", "SELECT t.id, o.name || '/' || t.name FROM teams t JOIN organisations o ON o.id = t.org_id WHERE t.id = $1"),
5ef6cf72 Andy McCall ↶ 1208
    ] {
1209
        let mut m = serde_json::Map::new();
1210
        for id in ids.get(kind).into_iter().flatten() {
1211
            if let Some((id, name)) = sqlx::query_as::<_, (i64, String)>(sql).bind(id).fetch_optional(pool).await? {
1212
                m.insert(id.to_string(), name.into());
1213
            }
1214
        }
1215
        out.insert(kind.into(), m.into());
1216
    }
1217
    Ok(out.into())
1218
}
1219
1220
/// The id `name` has on this hub as one of `_names`' kinds.
1221
async fn id_by_name(pool: &Pool, kind: &str, name: &str) -> Result<Option<i64>> {
1222
    Ok(match kind {
5d90e0e0 Andy McCall 1223
        "accounts" => sqlx::query_scalar("SELECT id FROM accounts WHERE username = $1").bind(name).fetch_optional(pool).await?,
1224
        "organisations" => sqlx::query_scalar("SELECT id FROM organisations WHERE name = $1").bind(name).fetch_optional(pool).await?,
5ef6cf72 Andy McCall ↶ 1225
        "teams" => match name.split_once('/') {
1226
            Some((org, team)) => {
5d90e0e0 Andy McCall 1227
                sqlx::query_scalar("SELECT t.id FROM teams t JOIN organisations o ON o.id = t.org_id WHERE o.name = $1 AND t.name = $2")
5ef6cf72 Andy McCall ↶ 1228
                    .bind(org)
1229
                    .bind(team)
1230
                    .fetch_optional(pool)
1231
                    .await?
1232
            }
1233
            None => None,
1234
        },
1235
        _ => None,
1236
    })
1237
}
1238
1239
/// One column of a table on this hub.
1240
struct Col {
1241
    name: String,
1242
    ty: String,
1243
    notnull: bool,
1244
    default: Option<String>,
1245
    pk: i64,
1246
}
1247
1248
async fn table_cols(pool: &Pool, table: &str) -> Result<Vec<Col>> {
3b1bc27f Andy McCall 1249
    catalog::cols(pool, table).await
5ef6cf72 Andy McCall ↶ 1250
}
1251
3b1bc27f Andy McCall 1252
/// Bind one value of a backed-up row to a column of type `ty`: blobs were
1253
/// written as hex, flags as 0 or 1 (a Postgres BOOLEAN takes them as such).
5ef6cf72 Andy McCall ↶ 1254
fn bind_json<'q>(
3b1bc27f Andy McCall 1255
    q: sqlx::query::Query<'q, crate::db::Db, <crate::db::Db as sqlx::Database>::Arguments<'q>>,
5ef6cf72 Andy McCall ↶ 1256
    v: serde_json::Value,
3b1bc27f Andy McCall 1257
    ty: &str,
1258
) -> sqlx::query::Query<'q, crate::db::Db, <crate::db::Db as sqlx::Database>::Arguments<'q>> {
1259
    let blob = ty.eq_ignore_ascii_case("BLOB");
1260
    if ty == "BOOLEAN" {
1261
        return match v {
1262
            serde_json::Value::Null => q.bind(None::<bool>),
1263
            serde_json::Value::Bool(b) => q.bind(b),
1264
            serde_json::Value::Number(n) => q.bind(n.as_f64().unwrap_or(0.0) != 0.0),
1265
            other => q.bind(matches!(other.as_str(), Some("1" | "true"))),
1266
        };
1267
    }
5ef6cf72 Andy McCall ↶ 1268
    match v {
1269
        serde_json::Value::Null => q.bind(None::<i64>),
1270
        serde_json::Value::Bool(b) => q.bind(b as i64),
1271
        serde_json::Value::Number(n) => match n.as_i64() {
1272
            Some(i) => q.bind(i),
1273
            None => q.bind(n.as_f64().unwrap_or(0.0)),
1274
        },
1275
        serde_json::Value::String(s) if blob => q.bind(hex::decode(&s).unwrap_or_else(|_| s.into_bytes())),
1276
        serde_json::Value::String(s) => q.bind(s),
1277
        other => q.bind(other.to_string()),
1278
    }
1279
}
1280
1281
/// Restore one repository's records from a run into this hub, the
1282
/// repository being `repo` here and `old` in the backup (docs/backups.md
1283
/// §7): its issues, proposals, labels, milestones, releases and their
1284
/// assets, checks, Flow runs and the rest, each table after the tables it
1285
/// points at, every id mapped to its new one and every account, team and
1286
/// organisation found again by name. A row pointing at an account this
1287
/// hub lacks keeps a blank reference where it may, and is left out where
1288
/// it may not. What needs re-entering (webhook secrets, never backed up)
1289
/// and what was left out come back as notes.
1290
async fn restore_records(
1291
    app: &Shared,
1292
    dest: &std::sync::Arc<dyn Destination>,
1293
    rec: &serde_json::Value,
1294
    old: i64,
1295
    repo: i64,
1296
) -> Result<Vec<String>> {
1297
    let pool = &app.db;
1298
    let obj = rec.as_object().context("the records are not an object")?;
1299
    let mut by_name: HashMap<(String, i64), Option<i64>> = HashMap::new();
1300
    for (kind, m) in obj.get(NAMES).and_then(|n| n.as_object()).into_iter().flatten() {
1301
        for (id, name) in m.as_object().into_iter().flatten() {
1302
            let (Ok(id), Some(name)) = (id.parse::<i64>(), name.as_str()) else { continue };
1303
            by_name.insert((kind.clone(), id), id_by_name(pool, kind, name).await?);
1304
        }
1305
    }
1306
    let here: std::collections::HashSet<String> = tables(pool).await?.into_iter().collect();
1307
    let mut notes = Vec::new();
1308
    let mut todo: Vec<String> = Vec::new();
1309
    for t in obj.keys().filter(|t| t.as_str() != "repositories" && !NOT_RESTORED.contains(&t.as_str())) {
1310
        if here.contains(t) {
1311
            todo.push(t.clone());
1312
        } else {
1313
            notes.push(format!("{t}: not a table on this hub, left out"));
1314
        }
1315
    }
1316
    let mut fks: HashMap<String, Vec<(String, String, String)>> = HashMap::new();
1317
    for t in &todo {
1318
        fks.insert(t.clone(), fk_list(pool, t).await?);
1319
    }
1320
    // Each table after the tables of the records it points at.
1321
    let mut order = Vec::new();
1322
    while !todo.is_empty() {
1323
        let mut ready: Vec<String> =
1324
            todo.iter().filter(|t| fks[*t].iter().all(|(p, _, _)| p == *t || !todo.contains(p))).cloned().collect();
1325
        if ready.is_empty() {
1326
            ready.push(todo[0].clone());
1327
        }
1328
        todo.retain(|t| !ready.contains(t));
1329
        order.extend(ready);
1330
    }
1331
    let mut maps: HashMap<String, HashMap<i64, i64>> = HashMap::new();
1332
    maps.insert("repositories".into(), [(old, repo)].into());
1333
    let mut left_out: std::collections::BTreeMap<String, usize> = Default::default();
1334
    let mut tx = pool.begin().await?;
1335
    for table in &order {
1336
        let cols = table_cols(pool, table).await?;
1337
        let keys: Vec<&str> = cols.iter().filter(|c| c.pk > 0).map(|c| c.name.as_str()).collect();
1338
        let by_id = keys == ["id"] && cols.iter().any(|c| c.name == "id" && c.ty.eq_ignore_ascii_case("INTEGER"));
1339
        let verb = if keys == ["repo_id"] {
3b1bc27f Andy McCall 1340
            Verb::Replace
5ef6cf72 Andy McCall ↶ 1341
        } else if by_id {
3b1bc27f Andy McCall 1342
            Verb::New
5ef6cf72 Andy McCall ↶ 1343
        } else {
3b1bc27f Andy McCall 1344
            Verb::Ignore
5ef6cf72 Andy McCall ↶ 1345
        };
1346
        let mut rows: Vec<&serde_json::Map<String, serde_json::Value>> =
1347
            obj[table].as_array().into_iter().flatten().filter_map(|r| r.as_object()).collect();
1348
        rows.sort_by_key(|r| r.get("id").and_then(|v| v.as_i64()).unwrap_or(0));
1349
        'row: for row in rows {
1350
            let (mut names, mut values) = (Vec::new(), Vec::new());
1351
            for c in &cols {
1352
                if by_id && c.name == "id" {
1353
                    continue;
1354
                }
1355
                let mut v = row.get(&c.name).cloned().filter(|v| !v.is_null());
1356
                if let Some((parent, _, _)) = fks[table].iter().find(|(_, from, _)| *from == c.name) {
1357
                    if let Some(was) = v.as_ref().and_then(|v| v.as_i64()) {
1358
                        let now = match parent.as_str() {
1359
                            "accounts" | "teams" | "organisations" => by_name.get(&(parent.clone(), was)).copied().flatten(),
1360
                            p => maps.get(p).and_then(|m| m.get(&was)).copied(),
1361
                        };
1362
                        if now.is_none() && c.notnull {
1363
                            *left_out.entry(table.clone()).or_default() += 1;
1364
                            continue 'row;
1365
                        }
1366
                        v = now.map(serde_json::Value::from);
1367
                    }
1368
                }
1369
                match v {
1370
                    Some(v) => {
1371
                        names.push(c.name.clone());
3b1bc27f Andy McCall 1372
                        values.push((v, c.ty.as_str()));
5ef6cf72 Andy McCall ↶ 1373
                    }
1374
                    // Never backed up (a secret): blank here, to enter again.
1375
                    None if c.notnull && c.default.is_none() => {
1376
                        names.push(c.name.clone());
3b1bc27f Andy McCall 1377
                        let blank = if c.ty.to_ascii_uppercase().contains("INT") || c.ty == "BOOLEAN" {
1378
                            serde_json::json!(0)
1379
                        } else {
1380
                            serde_json::json!("")
1381
                        };
1382
                        values.push((blank, c.ty.as_str()));
5ef6cf72 Andy McCall ↶ 1383
                    }
1384
                    None => {}
1385
                }
1386
            }
3b1bc27f Andy McCall 1387
            // A row with a new id says what it is (a plain INSERT, so one row).
1388
            let (insert, tail) = catalog::insert(verb, &names);
5ef6cf72 Andy McCall ↶ 1389
            let sql = format!(
3b1bc27f Andy McCall 1390
                "{insert} INTO \"{table}\" ({}) VALUES ({}){tail}{}",
5ef6cf72 Andy McCall ↶ 1391
                names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", "),
3b1bc27f Andy McCall 1392
                (1..=names.len()).map(|i| format!("${i}")).collect::<Vec<_>>().join(", "),
1393
                if by_id { " RETURNING id" } else { "" }
5ef6cf72 Andy McCall ↶ 1394
            );
1395
            let mut q = sqlx::query(&sql);
3b1bc27f Andy McCall 1396
            for (v, ty) in values {
1397
                q = bind_json(q, v, ty);
5ef6cf72 Andy McCall ↶ 1398
            }
3b1bc27f Andy McCall 1399
            let context = || format!("restore a row of {table}");
1400
            if by_id {
1401
                let made: i64 = sqlx::Row::try_get(&q.fetch_one(&mut *tx).await.with_context(context)?, 0)?;
1402
                if let Some(was) = row.get("id").and_then(|v| v.as_i64()) {
1403
                    maps.entry(table.clone()).or_default().insert(was, made);
1404
                }
1405
            } else {
1406
                q.execute(&mut *tx).await.with_context(context)?;
5ef6cf72 Andy McCall ↶ 1407
            }
1408
        }
1409
    }
1410
    tx.commit().await?;
1411
    for (table, n) in left_out {
1412
        notes.push(format!("{table}: {n} row(s) left out: they name accounts or rows this hub lacks"));
1413
    }
1414
    // Search finds what came back.
1415
    for (kind, table) in [("issue", "issues"), ("proposal", "proposals")] {
1416
        let found: Vec<(i64, i64, String, String)> =
5d90e0e0 Andy McCall 1417
            sqlx::query_as(&format!("SELECT id, number, title, body FROM {table} WHERE repo_id = $1")).bind(repo).fetch_all(pool).await?;
5ef6cf72 Andy McCall ↶ 1418
        for (id, number, title, body) in found {
1419
            db::notify::index(pool, kind, repo, id, number, &title, &body).await?;
1420
        }
1421
    }
1422
    // Webhook secrets were never written: they are entered again.
1423
    let hooks: Vec<String> =
5d90e0e0 Andy McCall 1424
        sqlx::query_scalar("SELECT url FROM hooks WHERE repo_id = $1 AND secret = ''").bind(repo).fetch_all(pool).await?;
5ef6cf72 Andy McCall ↶ 1425
    for url in hooks {
1426
        notes.push(format!("webhook {url}: enter its secret again (Settings › Webhooks)"));
1427
    }
1428
    // Release assets, each checked against its name.
1429
    for hash in obj.get("release_assets").and_then(|a| a.as_array()).into_iter().flatten().filter_map(|a| a["hash"].as_str()) {
1430
        if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
1431
            continue;
1432
        }
1433
        let path = crate::web::releases::blob_path(app, hash);
1434
        if path.exists() {
1435
            continue;
1436
        }
1437
        let got = tokio::task::block_in_place(|| dest.get(&blob_key(hash)));
1438
        match got {
1439
            Ok(bytes) if blake3::hash(&bytes).to_hex().as_str() == hash => {
1440
                std::fs::create_dir_all(path.parent().context("no parent")?)?;
1441
                std::fs::write(&path, &bytes)?;
1442
            }
1443
            Ok(_) => notes.push(format!("release asset {}: the copy does not match its hash", &hash[..12])),
1444
            Err(_) => notes.push(format!("release asset {}: not in the backup", &hash[..12])),
1445
        }
1446
    }
1447
    Ok(notes)
1448
}
1449
d7d18246 Andy McCall ↶ 1450
// ---------------------------------------------------------------- a run
1451
1452
fn run_name(ms: i64) -> String {
1453
    let t = time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
1454
    format!("{:04}{:02}{:02}T{:02}{:02}{:02}Z", t.year(), u8::from(t.month()), t.day(), t.hour(), t.minute(), t.second())
1455
}
1456
1457
/// The last whole run's manifests, by `kind/name`.
1458
fn last_manifests(dest: &dyn Destination) -> HashMap<String, HashMap<String, File>> {
1459
    let mut out = HashMap::new();
1460
    let Ok(at) = dest.get("LATEST").map(|b| String::from_utf8_lossy(&b).trim().to_string()) else { return out };
1461
    for name in dest.list(&format!("runs/{at}/repos")).unwrap_or_default() {
1462
        if let Ok(m) = dest.get(&format!("runs/{at}/repos/{name}")).and_then(|b| Ok(serde_json::from_slice::<Manifest>(&b)?)) {
1463
            out.insert(format!("{}/{}", m.kind, m.name), m.files.into_iter().map(|f| (f.path.clone(), f)).collect());
1464
        }
1465
    }
1466
    out
1467
}
1468
1469
/// Back up `owner` now, as its setting says. The run is recorded whatever
1470
/// happens; a failure notifies the owner once until a run succeeds.
1471
pub async fn run(app: &Shared, owner: &str, trigger: &str) -> Result<Run> {
1472
    let s = setting(&app.db, owner).await?.with_context(|| format!("{owner} has no backup set up"))?;
1473
    let started = db::now_ms();
1474
    let at = run_name(started);
5d90e0e0 Andy McCall 1475
    let id: i64 = sqlx::query_scalar(
1476
        "INSERT INTO backup_runs (owner, started_ms, status, at, trigger) VALUES ($1, $2, 'running', $3, $4) RETURNING id",
1477
    )
1478
    .bind(owner)
1479
    .bind(started)
1480
    .bind(&at)
1481
    .bind(trigger)
1482
    .fetch_one(&app.db)
1483
    .await?;
d3b048b2 Andy McCall ↶ 1484
    let outcome = run_into(app, &s, &at, trigger == "now").await;
d7d18246 Andy McCall ↶ 1485
    let (status, detail, sent) = match outcome {
1486
        Ok((sent, problems)) if problems.is_empty() => ("ok", String::new(), sent),
1487
        Ok((sent, problems)) => ("partial", problems.join("; "), sent),
1488
        Err(e) => ("failed", format!("{e:#}"), (0, Sent::default())),
1489
    };
5d90e0e0 Andy McCall 1490
    sqlx::query(
1491
        "UPDATE backup_runs SET finished_ms = $1, status = $2, detail = $3, repos = $4, files = $5, sent = $6, bytes = $7 WHERE id = $8",
1492
    )
1493
    .bind(db::now_ms())
1494
    .bind(status)
1495
    .bind(&detail)
1496
    .bind(sent.0)
1497
    .bind(sent.1.files)
1498
    .bind(sent.1.sent)
1499
    .bind(sent.1.bytes)
1500
    .bind(id)
1501
    .execute(&app.db)
1502
    .await?;
1503
    let r: Run = sqlx::query_as("SELECT * FROM backup_runs WHERE id = $1").bind(id).fetch_one(&app.db).await?;
d7d18246 Andy McCall ↶ 1504
    if status != "ok" {
1505
        notify_failure(app, &s, status, &detail).await;
bff9106e Andy McCall ↶ 1506
    } else {
1507
        notify_recovered(app, &s, &r).await;
d7d18246 Andy McCall ↶ 1508
    }
1509
    Ok(r)
1510
}
1511
d3b048b2 Andy McCall ↶ 1512
async fn run_into(app: &Shared, s: &Setting, at: &str, by_hand: bool) -> Result<((i64, Sent), Vec<String>)> {
d7d18246 Andy McCall ↶ 1513
    let dest: std::sync::Arc<dyn Destination> = destination(app, s)?.into();
1514
    let known = {
1515
        let d = dest.clone();
1516
        tokio::task::spawn_blocking(move || last_manifests(d.as_ref())).await?
1517
    };
d3b048b2 Andy McCall ↶ 1518
    // Its repositories, but those left out (§5).
1519
    let mine: Vec<db::repos::RepoRow> =
1520
        db::repos::list(&app.db).await?.into_iter().filter(|r| r.owner == s.owner && included(s, r, by_hand)).collect();
d7d18246 Andy McCall ↶ 1521
    let mut problems = Vec::new();
1522
    let mut sent = Sent::default();
1523
    let mut repos = 0i64;
1524
    for row in &mine {
1525
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
1526
        for (kind, store) in [("repos", &app.repos), ("wikis", &app.wikis)] {
1527
            if !store.exists(&name) {
1528
                continue;
1529
            }
1530
            let dir = store.dir(&name);
1531
            let k = known.get(&format!("{kind}/{}", row.name)).cloned().unwrap_or_default();
1532
            // The large, unchanging files without the lock, then the whole
1533
            // walk again under the read lock: pushes wait for that moment.
1534
            let (d1, dir1, k1) = (dest.clone(), dir.clone(), k.clone());
1535
            let first = tokio::task::spawn_blocking(move || {
1536
                let mut s = Sent::default();
1537
                copy_dir(d1.as_ref(), &dir1, &k1, true, &mut s).map(|f| (f, s))
1538
            })
1539
            .await?;
1540
            let mut k2 = k;
1541
            if let Ok((files, _)) = &first {
1542
                for f in files {
1543
                    k2.insert(f.path.clone(), f.clone());
1544
                }
1545
            }
7c06f5b2 Andy McCall ↶ 1546
            // Writers wait while the last pass copies (readers carry on),
1547
            // so the refs copied name only objects copied (#249).
1548
            let guard = store.write_guard(&name).await;
d7d18246 Andy McCall ↶ 1549
            let (d2, dir2) = (dest.clone(), dir.clone());
1550
            let second = tokio::task::spawn_blocking(move || {
1551
                let _guard = guard;
1552
                let mut s = Sent::default();
1553
                copy_dir(d2.as_ref(), &dir2, &k2, false, &mut s).map(|f| (f, s))
1554
            })
1555
            .await?;
1556
            match second {
1557
                Ok((files, s2)) => {
1558
                    let s1 = first.map(|(_, s)| s).unwrap_or_default();
1559
                    sent.files += s2.files;
1560
                    sent.sent += s1.sent + s2.sent;
1561
                    sent.bytes += s1.bytes + s2.bytes;
1562
                    let m = Manifest { owner: row.owner.clone(), name: row.name.clone(), kind: kind.into(), files };
1563
                    let key = format!("runs/{at}/repos/{kind}-{}.json", row.name);
35fea423 Andy McCall ↶ 1564
                    tokio::task::block_in_place(|| dest.put(&key, &serde_json::to_vec(&m)?))?;
d7d18246 Andy McCall ↶ 1565
                    if kind == "repos" {
1566
                        repos += 1;
1567
                    }
1568
                }
1569
                Err(e) => problems.push(format!("{}/{} ({kind}): {e:#}", row.owner, row.name)),
1570
            }
1571
        }
1572
        let rec = async {
1573
            let mut r = records(&app.db, "repo_id", row.id).await?;
5ef6cf72 Andy McCall ↶ 1574
            // The repository's own row, which restore recreates first, and
1575
            // the names behind the accounts, teams and organisations its
1576
            // rows point at, which another hub finds them by.
d7d18246 Andy McCall ↶ 1577
            let own = rows(&app.db, "repositories", &format!("id = {}", row.id)).await?;
5ef6cf72 Andy McCall ↶ 1578
            let names = names_of(&app.db, &r).await?;
d7d18246 Andy McCall ↶ 1579
            if let Some(m) = r.as_object_mut() {
1580
                m.insert("repositories".into(), own);
5ef6cf72 Andy McCall ↶ 1581
                m.insert(NAMES.into(), names);
d7d18246 Andy McCall ↶ 1582
            }
1583
            anyhow::Ok(r)
1584
        };
1585
        match rec.await {
5ef6cf72 Andy McCall ↶ 1586
            Ok(r) => {
1587
                tokio::task::block_in_place(|| dest.put(&format!("runs/{at}/records/{}.json", row.name), &serde_json::to_vec(&r)?))?;
1588
                // Release assets live beside the stores, named by their
1589
                // BLAKE3: each sent once, as the stores' files are.
1590
                for hash in r["release_assets"].as_array().into_iter().flatten().filter_map(|a| a["hash"].as_str()) {
1591
                    if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
1592
                        continue;
1593
                    }
1594
                    let path = crate::web::releases::blob_path(app, hash);
1595
                    let key = blob_key(hash);
1596
                    let put = tokio::task::block_in_place(|| -> Result<Option<i64>> {
1597
                        if dest.exists(&key)? {
1598
                            return Ok(None);
1599
                        }
1600
                        let bytes = std::fs::read(&path).with_context(|| format!("read release asset {}", &hash[..12]))?;
1601
                        dest.put(&key, &bytes)?;
1602
                        Ok(Some(bytes.len() as i64))
1603
                    });
1604
                    match put {
1605
                        Ok(Some(n)) => {
1606
                            sent.files += 1;
1607
                            sent.sent += 1;
1608
                            sent.bytes += n;
1609
                        }
1610
                        Ok(None) => sent.files += 1,
1611
                        Err(e) => problems.push(format!("{}/{} release asset: {e:#}", row.owner, row.name)),
1612
                    }
1613
                }
1614
            }
d7d18246 Andy McCall ↶ 1615
            Err(e) => problems.push(format!("{}/{} records: {e:#}", row.owner, row.name)),
1616
        }
1617
    }
1618
    // The owner itself.
1619
    let owner_rows = if s.kind == "org" {
1620
        match db::accounts::org_by_name(&app.db, &s.owner).await? {
1621
            Some(o) => records(&app.db, "org_id", o.id).await?,
1622
            None => serde_json::json!({}),
1623
        }
1624
    } else {
1625
        match db::accounts::account_by_name(&app.db, &s.owner).await? {
1626
            Some(a) => records(&app.db, "account_id", a.id).await?,
1627
            None => serde_json::json!({}),
1628
        }
1629
    };
35fea423 Andy McCall ↶ 1630
    // The blocking calls of a destination (GCS drives its client on this
1631
    // runtime) run where blocking is allowed.
1632
    tokio::task::block_in_place(|| -> Result<()> {
1633
        dest.put(&format!("runs/{at}/owner.json"), &serde_json::to_vec(&owner_rows)?)?;
1634
        dest.put(&format!("runs/{at}/DONE"), at.as_bytes())?;
1635
        dest.put("LATEST", at.as_bytes())?;
1636
        prune(dest.as_ref(), s.keep_days)
1637
    })?;
d7d18246 Andy McCall ↶ 1638
    Ok(((repos, sent), problems))
1639
}
1640
1641
/// Drop whole runs older than `keep_days`, and the blobs no kept run
1642
/// names. The newest whole run is always kept.
1643
pub fn prune(dest: &dyn Destination, keep_days: i64) -> Result<()> {
1644
    let cutoff = run_name(db::now_ms() - keep_days.max(1) * 86_400_000);
1645
    let runs = dest.list("runs")?;
1646
    let whole: Vec<&String> = runs.iter().filter(|r| dest.exists(&format!("runs/{r}/DONE")).unwrap_or(false)).collect();
1647
    let newest = whole.last().map(|s| s.to_string());
1648
    let mut removed = false;
1649
    for r in &runs {
1650
        if r.as_str() < cutoff.as_str() && Some(r.to_string()) != newest {
1651
            dest.remove(&format!("runs/{r}"))?;
1652
            removed = true;
1653
        }
1654
    }
1655
    if !removed {
1656
        return Ok(());
1657
    }
1658
    let mut wanted = std::collections::HashSet::new();
1659
    for r in dest.list("runs")? {
1660
        for m in dest.list(&format!("runs/{r}/repos"))? {
1661
            if let Ok(m) = dest.get(&format!("runs/{r}/repos/{m}")).and_then(|b| Ok(serde_json::from_slice::<Manifest>(&b)?)) {
1662
                wanted.extend(m.files.into_iter().map(|f| f.hash));
1663
            }
1664
        }
1665
    }
1666
    for shard in dest.list("blobs")? {
1667
        for b in dest.list(&format!("blobs/{shard}"))? {
1668
            if !wanted.contains(&b) {
1669
                dest.remove(&format!("blobs/{shard}/{b}"))?;
1670
            }
1671
        }
1672
    }
1673
    Ok(())
bff9106e Andy McCall ↶ 1674
}
1675
1676
/// Who hears about `s`'s backups, and where they look: the user, or the
1677
/// organisation's owners.
1678
async fn told(app: &Shared, s: &Setting) -> Option<(Vec<(i64, db::notify::Reason)>, String)> {
1679
    let p = db::notify::Reason::Participating;
1680
    if s.kind == "org" {
1681
        let o = db::accounts::org_by_name(&app.db, &s.owner).await.ok().flatten()?;
1682
        let owners = db::accounts::org_members(&app.db, o.id)
1683
            .await
1684
            .ok()?
1685
            .into_iter()
1686
            .filter(|(_, r)| r == "owner")
1687
            .map(|(a, _)| (a.id, p))
1688
            .collect();
1689
        Some((owners, format!("/orgs/{}/settings/backups", s.owner)))
1690
    } else {
1691
        let a = db::accounts::account_by_name(&app.db, &s.owner).await.ok().flatten()?;
1692
        Some((vec![(a.id, p)], "/settings/backups".into()))
1693
    }
1694
}
1695
1696
/// The status of `owner`'s finished run before the newest.
1697
async fn status_before(app: &Shared, owner: &str) -> Option<String> {
5d90e0e0 Andy McCall 1698
    sqlx::query_scalar("SELECT status FROM backup_runs WHERE owner = $1 AND finished_ms IS NOT NULL ORDER BY id DESC LIMIT 1 OFFSET 1")
bff9106e Andy McCall ↶ 1699
        .bind(owner)
1700
        .fetch_optional(&app.db)
1701
        .await
1702
        .ok()
1703
        .flatten()
d7d18246 Andy McCall ↶ 1704
}
1705
bff9106e Andy McCall ↶ 1706
/// A run that did not finish whole tells the owner (inbox and email), once
1707
/// per spell of failures: not when the run before failed too.
d7d18246 Andy McCall ↶ 1708
async fn notify_failure(app: &Shared, s: &Setting, status: &str, detail: &str) {
bff9106e Andy McCall ↶ 1709
    if status_before(app, &s.owner).await.is_some_and(|b| b != "ok") {
1710
        return;
1711
    }
1712
    let Some((who, url)) = told(app, s).await else { return };
1713
    let title = format!("Backup of {} {status}: {}", s.owner, detail.chars().take(160).collect::<String>());
1714
    crate::notify::tell(app, "backup", &title, &url, "backups", None, who).await;
1715
}
1716
1717
/// A whole run after one that was not: the owner hears it works again
1718
/// (oxygenhub#183).
1719
async fn notify_recovered(app: &Shared, s: &Setting, run: &Run) {
1720
    if !status_before(app, &s.owner).await.is_some_and(|b| b != "ok") {
d7d18246 Andy McCall ↶ 1721
        return;
bff9106e Andy McCall ↶ 1722
    }
1723
    let Some((who, url)) = told(app, s).await else { return };
1724
    let title = format!("Backup of {} works again: {} repositories to {}", s.owner, run.repos, place(s));
1725
    crate::notify::tell(app, "backup.recovered", &title, &url, "backups", None, who).await;
1726
}
1727
1728
/// The hour (UTC) each day's backup summary goes out.
1729
const SUMMARY_HOUR: u8 = 7;
1730
const SUMMARY_SENT: &str = "backups.summary_day";
1731
1732
/// One message a day per owner (oxygenhub#183): the last day's runs, how
1733
/// they went and what they sent. Sent at the first scheduler tick from
1734
/// SUMMARY_HOUR (UTC), once a day. How many owners were told.
1735
pub async fn daily_summary(app: &Shared, now_ms: i64, force: bool) -> sqlx::Result<usize> {
1736
    let t = time::OffsetDateTime::from_unix_timestamp_nanos(now_ms as i128 * 1_000_000).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
1737
    let day = format!("{:04}-{:02}-{:02}", t.year(), u8::from(t.month()), t.day());
1738
    if !force && (t.hour() < SUMMARY_HOUR || db::accounts::setting(&app.db, SUMMARY_SENT).await?.as_deref() == Some(day.as_str())) {
1739
        return Ok(0);
d7d18246 Andy McCall ↶ 1740
    }
bff9106e Andy McCall ↶ 1741
    db::accounts::set_setting(&app.db, SUMMARY_SENT, &day).await?;
1742
    let settings: Vec<Setting> = sqlx::query_as("SELECT * FROM backup_settings WHERE updated_ms > 0").fetch_all(&app.db).await?;
1743
    let mut sent = 0;
1744
    for s in settings {
5d90e0e0 Andy McCall 1745
        let runs: Vec<Run> = sqlx::query_as("SELECT * FROM backup_runs WHERE owner = $1 AND started_ms >= $2 ORDER BY id")
bff9106e Andy McCall ↶ 1746
            .bind(&s.owner)
1747
            .bind(now_ms - 86_400_000)
1748
            .fetch_all(&app.db)
1749
            .await?;
1750
        if runs.is_empty() {
1751
            continue;
d7d18246 Andy McCall ↶ 1752
        }
bff9106e Andy McCall ↶ 1753
        let ok = runs.iter().filter(|r| r.status == "ok").count();
1754
        let bytes: i64 = runs.iter().map(|r| r.bytes).sum();
1755
        let repos = runs.iter().rev().find(|r| r.status == "ok").map_or(0, |r| r.repos);
1756
        let how = if ok == runs.len() { "all ok".to_string() } else { format!("{} not whole", runs.len() - ok) };
1757
        let title = format!(
1758
            "Backups of {} today: {} runs, {how}, {repos} repositories, {:.1} MiB sent to {}",
1759
            s.owner,
1760
            runs.len(),
1761
            bytes as f64 / 1_048_576.0,
1762
            place(&s)
1763
        );
1764
        let Some((who, url)) = told(app, &s).await else { continue };
1765
        crate::notify::tell(app, "backup.summary", &title, &url, "backups", None, who).await;
1766
        sent += 1;
d7d18246 Andy McCall ↶ 1767
    }
bff9106e Andy McCall ↶ 1768
    Ok(sent)
d7d18246 Andy McCall ↶ 1769
}
1770
1771
/// Run each owner's backup when it is due, one at a time. A run left
1772
/// "running" by a restart is marked failed first.
1773
pub async fn scheduler(app: Shared) {
1774
    let _ = sqlx::query(
5d90e0e0 Andy McCall 1775
        "UPDATE backup_runs SET status = 'failed', detail = 'the hub restarted during the run', finished_ms = $1 WHERE status = 'running'",
d7d18246 Andy McCall ↶ 1776
    )
1777
    .bind(db::now_ms())
1778
    .execute(&app.db)
1779
    .await;
1780
    loop {
1781
        tokio::time::sleep(std::time::Duration::from_secs(60)).await;
bff9106e Andy McCall ↶ 1782
        if let Err(e) = daily_summary(&app, db::now_ms(), false).await {
1783
            tracing::warn!("backup summary: {e}");
1784
        }
d7d18246 Andy McCall ↶ 1785
        for s in due(&app.db).await.unwrap_or_default() {
1786
            if let Err(e) = run(&app, &s.owner, "schedule").await {
1787
                tracing::warn!("backup of {}: {e:#}", s.owner);
1788
            }
1789
        }
1790
    }
1791
}
1792
d3b048b2 Andy McCall ↶ 1793
/// The owners whose next run is due now: by their own schedule, or by
1794
/// the shortest schedule one of their repositories chose (§5). A run takes
1795
/// every included repository and sends only what changed, so each run
1796
/// stays whole and a restore point has everything.
d7d18246 Andy McCall ↶ 1797
pub async fn due(pool: &Pool) -> sqlx::Result<Vec<Setting>> {
d3b048b2 Andy McCall ↶ 1798
    let all: Vec<Setting> = sqlx::query_as("SELECT * FROM backup_settings WHERE updated_ms > 0").fetch_all(pool).await?;
1799
    let repos = db::repos::list(pool).await?;
d7d18246 Andy McCall ↶ 1800
    let now = db::now_ms();
1801
    let mut out = Vec::new();
1802
    for s in all {
d3b048b2 Andy McCall ↶ 1803
        let theirs: Vec<db::repos::RepoRow> = repos.iter().filter(|r| r.owner == s.owner).cloned().collect();
1804
        let Some(period) = period_with(&s, &theirs) else { continue };
d7d18246 Andy McCall ↶ 1805
        let last: Option<i64> =
5d90e0e0 Andy McCall 1806
            sqlx::query_scalar("SELECT MAX(started_ms) FROM backup_runs WHERE owner = $1").bind(&s.owner).fetch_one(pool).await?;
d7d18246 Andy McCall ↶ 1807
        if last.is_none_or(|l| now - l >= period * 1000) {
1808
            out.push(s);
1809
        }
1810
    }
1811
    Ok(out)
1812
}
1813
1814
/// Restore every repository of the whole run `at` (the latest when none)
1815
/// from `dest` into `repos_root/OWNER/NAME` and `wikis_root/…`, refusing to
1816
/// overwrite one that exists. Each file is checked against its hash.
1817
pub fn restore(dest: &dyn Destination, at: Option<&str>, repos_root: &Path, wikis_root: &Path) -> Result<Vec<String>> {
1818
    let at = match at {
1819
        Some(a) => a.to_string(),
1820
        None => String::from_utf8_lossy(&dest.get("LATEST").context("no whole run at this destination")?).trim().to_string(),
1821
    };
1822
    if !dest.exists(&format!("runs/{at}/DONE"))? {
1823
        bail!("run {at} is not whole (no DONE): pick another with --run");
1824
    }
1825
    let mut done = Vec::new();
1826
    for name in dest.list(&format!("runs/{at}/repos"))? {
1827
        let m: Manifest = serde_json::from_slice(&dest.get(&format!("runs/{at}/repos/{name}"))?)?;
1828
        let root = if m.kind == "wikis" { wikis_root } else { repos_root };
1829
        let dir = root.join(&m.owner).join(&m.name);
1830
        if dir.exists() {
1831
            bail!("{} exists: restore into an empty hub, or move it aside", dir.display());
1832
        }
1833
        for f in &m.files {
1834
            let bytes = dest.get(&blob_key(&f.hash))?;
1835
            if blake3::hash(&bytes).to_hex().as_str() != f.hash {
1836
                bail!("{}/{} {}: the copy does not match its hash", m.owner, m.name, f.path);
1837
            }
1838
            let p = dir.join(&f.path);
1839
            std::fs::create_dir_all(p.parent().context("no parent")?)?;
1840
            std::fs::write(&p, &bytes)?;
1841
        }
1842
        done.push(format!("{}/{} ({})", m.owner, m.name, m.kind));
1843
    }
1844
    Ok(done)
1845
}
1846
1847
/// Restore the whole run `at` (the latest when none) into this hub: each
5ef6cf72 Andy McCall ↶ 1848
/// repository's and wiki's store byte for byte, then its row and settings,
1849
/// then its records (issues, proposals, releases and the rest), so it shows
1850
/// on the hub as it was (docs/backups.md §7). What was restored, then any
1851
/// notes (`note: …`) on what needs entering again or was left out.
d7d18246 Andy McCall ↶ 1852
pub async fn restore_into_hub(app: &Shared, dest: std::sync::Arc<dyn Destination>, at: Option<String>) -> Result<Vec<String>> {
1853
    let (repos_root, wikis_root) = (app.repos.root().to_path_buf(), app.wikis.root().to_path_buf());
1854
    let (d, a) = (dest.clone(), at.clone());
1855
    let done = tokio::task::spawn_blocking(move || restore(d.as_ref(), a.as_deref(), &repos_root, &wikis_root)).await??;
1856
    let at = match at {
1857
        Some(a) => a,
35fea423 Andy McCall ↶ 1858
        None => String::from_utf8_lossy(&tokio::task::block_in_place(|| dest.get("LATEST"))?).trim().to_string(),
d7d18246 Andy McCall ↶ 1859
    };
5ef6cf72 Andy McCall ↶ 1860
    let mut notes = Vec::new();
35fea423 Andy McCall ↶ 1861
    for name in tokio::task::block_in_place(|| dest.list(&format!("runs/{at}/records")))? {
1862
        let rec: serde_json::Value =
1863
            serde_json::from_slice(&tokio::task::block_in_place(|| dest.get(&format!("runs/{at}/records/{name}")))?)?;
d7d18246 Andy McCall ↶ 1864
        let Some(row) = rec["repositories"].as_array().and_then(|a| a.first()) else { continue };
1865
        let (owner, repo) = (row["owner"].as_str().unwrap_or_default(), row["name"].as_str().unwrap_or_default());
1866
        if owner.is_empty() || db::repos::get(&app.db, owner, repo).await?.is_some() {
1867
            continue;
1868
        }
1869
        let visibility = match row["visibility"].as_str() {
1870
            Some("private") => hub_api::Visibility::Private,
1871
            Some("internal") => hub_api::Visibility::Internal,
1872
            _ => hub_api::Visibility::Public,
1873
        };
1874
        let made = db::repos::create(&app.db, owner, repo, row["description"].as_str().unwrap_or_default(), visibility).await?;
5ef6cf72 Andy McCall ↶ 1875
        // Its settings as they were: every column the row kept but its
1876
        // name, its id and a fork's parent (another hub's id).
1877
        let cols = table_cols(&app.db, "repositories").await?;
1878
        let set: Vec<(&Col, serde_json::Value)> = cols
1879
            .iter()
1880
            .filter(|c| !["id", "owner", "name", "forked_from"].contains(&c.name.as_str()))
1881
            .filter_map(|c| row.get(&c.name).filter(|v| !v.is_null()).map(|v| (c, v.clone())))
1882
            .collect();
1883
        if !set.is_empty() {
1884
            let sql = format!(
5d90e0e0 Andy McCall 1885
                "UPDATE repositories SET {} WHERE id = ${}",
1886
                set.iter().enumerate().map(|(i, (c, _))| format!("\"{}\" = ${}", c.name, i + 1)).collect::<Vec<_>>().join(", "),
1887
                set.len() + 1
5ef6cf72 Andy McCall ↶ 1888
            );
1889
            let mut q = sqlx::query(&sql);
1890
            for (c, v) in set {
3b1bc27f Andy McCall 1891
                q = bind_json(q, v, &c.ty);
5ef6cf72 Andy McCall ↶ 1892
            }
1893
            q.bind(made.id).execute(&app.db).await?;
1894
        }
1895
        let old = row["id"].as_i64().unwrap_or(-1);
1896
        for n in restore_records(app, &dest, &rec, old, made.id).await.with_context(|| format!("restore {owner}/{repo}'s records"))? {
1897
            notes.push(format!("note: {owner}/{repo}: {n}"));
d7d18246 Andy McCall ↶ 1898
        }
1899
    }
5ef6cf72 Andy McCall ↶ 1900
    let mut done = done;
1901
    done.extend(notes);
d7d18246 Andy McCall ↶ 1902
    Ok(done)
1903
}
1904
1905
#[cfg(test)]
1906
mod tests {
1907
    use super::*;
1908
1909
    #[test]
1910
    fn a_directory_destination_keeps_keys_inside_its_root() {
1911
        let d = tempfile::tempdir().unwrap();
1912
        let dest = Directory { root: d.path().to_path_buf() };
1913
        dest.put("runs/a/DONE", b"a").unwrap();
1914
        assert_eq!(dest.get("runs/a/DONE").unwrap(), b"a");
1915
        assert_eq!(dest.list("runs").unwrap(), vec!["a"]);
1916
        assert!(dest.put("../escape", b"x").is_err() && dest.put("/abs", b"x").is_err());
1917
        dest.remove("runs").unwrap();
1918
        assert!(dest.list("runs").unwrap().is_empty());
1919
    }
1920
1921
    #[test]
1922
    fn files_are_sent_once_and_unchanged_ones_not_read_again() {
1923
        let src = tempfile::tempdir().unwrap();
1924
        let out = tempfile::tempdir().unwrap();
1925
        let dest = Directory { root: out.path().to_path_buf() };
1926
        std::fs::create_dir_all(src.path().join(".oxy/objects/loose")).unwrap();
1927
        std::fs::write(src.path().join(".oxy/objects/loose/aa"), b"object").unwrap();
1928
        std::fs::write(src.path().join(".oxy/ops-head"), b"ref one").unwrap();
1929
        let mut s = Sent::default();
1930
        let files = copy_dir(&dest, src.path(), &HashMap::new(), false, &mut s).unwrap();
1931
        assert_eq!((files.len(), s.sent), (2, 2));
1932
        let known: HashMap<String, File> = files.iter().map(|f| (f.path.clone(), f.clone())).collect();
1933
        let mut s = Sent::default();
1934
        let again = copy_dir(&dest, src.path(), &known, false, &mut s).unwrap();
1935
        assert_eq!((again, s.sent), (files.clone(), 0), "nothing new travels");
1936
        // The first pass takes only the files that never change.
1937
        let mut s = Sent::default();
1938
        let first = copy_dir(&dest, src.path(), &HashMap::new(), true, &mut s).unwrap();
1939
        assert_eq!(first.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), vec![".oxy/objects/loose/aa"]);
7b9f4570 Andy McCall ↶ 1940
    }
1941
1942
    #[test]
1943
    fn requests_are_signed_as_aws_documents() {
1944
        // AWS's own example (S3 API reference, "Signature calculations":
cb7b3cd4 Andy McCall ↶ 1945
        // GET Object), with its published signature. Its documented example
1946
        // keys are put together at run time, so this file is not itself a
1947
        // push protection or history scan finding (#277).
1948
        let key_id = format!("{}{}", "AKIA", "IOSFODNN7EXAMPLE");
1949
        let secret = format!("{}{}", "wJalrXUtnFEMI/K7MDENG/", "bPxRfiCYEXAMPLEKEY");
7b9f4570 Andy McCall ↶ 1950
        let empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
1951
        let headers = vec![
1952
            ("Host".to_string(), "examplebucket.s3.amazonaws.com".to_string()),
1953
            ("Range".to_string(), "bytes=0-9".to_string()),
1954
            ("x-amz-content-sha256".to_string(), empty.to_string()),
1955
            ("x-amz-date".to_string(), "20130524T000000Z".to_string()),
1956
        ];
cb7b3cd4 Andy McCall ↶ 1957
        let auth =
1958
            sigv4("GET", "/test.txt", &[], &headers, empty, (key_id.as_str(), secret.as_str()), "us-east-1", "s3", "20130524T000000Z");
7b9f4570 Andy McCall ↶ 1959
        assert_eq!(
1960
            auth,
cb7b3cd4 Andy McCall ↶ 1961
            format!(
1962
                "AWS4-HMAC-SHA256 Credential={key_id}/20130524/us-east-1/s3/aws4_request, \
1963
                 SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, \
1964
                 Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
1965
            )
7b9f4570 Andy McCall ↶ 1966
        );
1967
        assert_eq!(aws_encode("runs/2026 x+y", true), "runs/2026%20x%2By");
1968
        assert_eq!(aws_encode("a/b", false), "a%2Fb");
1969
        assert_eq!(xml_text("<A><Key>runs/x&amp;y</Key></A>", "Key").as_deref(), Some("runs/x&y"));
d7d18246 Andy McCall ↶ 1970
    }
1971
1972
    #[test]
1973
    fn run_names_sort_by_time() {
1974
        assert_eq!(run_name(0), "19700101T000000Z");
1975
        assert!(run_name(1_791_900_000_000) < run_name(1_791_903_600_000));
1976
    }
1977
}