OXYGENHUB
# 9aaa88b2d9c8 oxygenhub / crates / hub / src / diffusion.rs
33.0 KiB · Rust · last changed Diffusion: an upstream without checks is amber, not green 23 days ago source blame history raw
f677d627 Andy McCall ↶ 1
//! Diffusion (#148, docs/diffusion.md): an upstream's changes reach the
2
//! repositories that pin it as a subrepo.
3
//!
4
//! D1 starts with the reverse pin index (§4.1): when a push moves a
5
//! repository's default bookmark, or the bookmark its work lands on, each
6
//! Oxygen subrepo pin in the new state is recorded. That answers "who
7
//! consumes this repository, at which state, and how far behind", which
8
//! an upstream's page shows as Used by.
9
10
use crate::auth::roles;
11
use crate::db::{self, accounts::Account, repos::RepoRow, Pool};
12
use crate::repos::RepoName;
13
use crate::Shared;
14
use oxy_core::hash::ChangeHash;
15
use serde::Serialize;
16
17
/// How far back landed proposals teach where a repository's work lands.
18
pub const LEARN_DAYS: i64 = 90;
19
20
/// The bookmark a repository's work lands on (§4.3): the most common
21
/// target of its proposals landed in the last `LEARN_DAYS`, else its
22
/// default bookmark.
23
pub async fn target(pool: &Pool, row: &RepoRow) -> String {
24
    let since = db::now_ms() - LEARN_DAYS * 24 * 3600 * 1000;
25
    let learned: Option<String> = sqlx::query_scalar(
26
        "SELECT target FROM proposals WHERE repo_id = ? AND state = 'landed' AND landed_ms >= ?
27
         GROUP BY target ORDER BY COUNT(*) DESC, MAX(landed_ms) DESC LIMIT 1",
28
    )
29
    .bind(row.id)
30
    .bind(since)
31
    .fetch_optional(pool)
32
    .await
33
    .ok()
34
    .flatten();
35
    learned.filter(|t| !t.is_empty()).unwrap_or_else(|| row.default_bookmark.clone())
36
}
37
38
/// The bookmarks whose pins are indexed: the default and the learned
39
/// target (one when they are the same).
40
pub async fn followed_bookmarks(pool: &Pool, row: &RepoRow) -> Vec<String> {
41
    let mut out = vec![row.default_bookmark.clone()];
42
    let t = target(pool, row).await;
43
    if !out.contains(&t) {
44
        out.push(t);
45
    }
46
    out
47
}
48
49
/// Record `row`'s pins on `bookmark` at `heads`, replacing what was there.
50
pub async fn record(app: &Shared, row: &RepoRow, bookmark: &str, heads: &[ChangeHash]) {
51
    let Some(name) = RepoName::new(&row.owner, &row.name) else { return };
52
    let pins = if heads.is_empty() { Vec::new() } else { crate::flow::pins_in(app, name, heads.to_vec()).await };
53
    let now = db::now_ms();
54
    let Ok(mut tx) = app.db.begin().await else { return };
55
    let mut ok = sqlx::query("DELETE FROM diffusion_pins WHERE consumer_id = ? AND bookmark = ?")
56
        .bind(row.id)
57
        .bind(bookmark)
58
        .execute(&mut *tx)
59
        .await
60
        .is_ok();
61
    for (path, id, pinned) in &pins {
62
        let heads: Vec<String> = pinned.iter().map(|h| h.to_hex()).collect();
63
        ok &=
64
            sqlx::query("INSERT INTO diffusion_pins (consumer_id, bookmark, path, upstream, heads, updated_ms) VALUES (?, ?, ?, ?, ?, ?)")
65
                .bind(row.id)
66
                .bind(bookmark)
67
                .bind(path)
68
                .bind(hex::encode(id))
69
                .bind(heads.join("+"))
70
                .bind(now)
71
                .execute(&mut *tx)
72
                .await
73
                .is_ok();
74
    }
75
    if ok {
76
        tx.commit().await.ok();
77
    }
78
}
79
80
/// After a push: index the pins of each moved bookmark that is followed.
81
pub async fn after_push(app: &Shared, row: &RepoRow, moved: &[(String, String, Vec<ChangeHash>)]) {
82
    let followed = followed_bookmarks(&app.db, row).await;
83
    for (bookmark, _, heads) in moved {
84
        if followed.contains(bookmark) {
85
            record(app, row, bookmark, heads).await;
86
        }
87
    }
88
}
89
90
/// Index every repository's followed bookmarks, for a hub that had no
91
/// index before (run once at start, in the background).
92
pub async fn backfill(app: &Shared) {
93
    let Ok(rows) = db::repos::list(&app.db).await else { return };
94
    for row in rows {
95
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
96
        for bookmark in followed_bookmarks(&app.db, &row).await {
97
            let b = bookmark.clone();
98
            let heads = app.repos.read(&name, move |r, _| heads_of(r, &b)).await;
99
            if let Ok(heads) = heads {
100
                record(app, &row, &bookmark, &heads).await;
101
            }
102
        }
103
    }
104
}
105
106
/// A bookmark's heads as the repository has them now (not a cached
107
/// list, which a push refreshes a moment later); empty when it has none.
108
fn heads_of(r: &oxy_core::repo::Repo, bookmark: &str) -> Result<Vec<ChangeHash>, crate::repos::RepoError> {
109
    Ok(r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default())
110
}
111
112
/// One consumer of an upstream, as an upstream's page and API show it.
113
#[derive(Clone, Debug, Serialize)]
114
pub struct Consumer {
115
    pub owner: String,
116
    pub name: String,
117
    pub bookmark: String,
118
    pub path: String,
119
    /// The upstream heads it pins, hex.
120
    pub pinned: Vec<String>,
121
    /// Upstream changes on its default bookmark the pin lacks; `None` when
122
    /// the hub cannot tell (the pinned changes are not in the upstream).
123
    pub behind: Option<usize>,
124
}
125
126
/// The consumers of `row` that `account` may read, with how far behind
127
/// the upstream's default bookmark each pin is.
128
pub async fn consumers(app: &Shared, row: &RepoRow, account: Option<&Account>) -> Result<Vec<Consumer>, crate::repos::RepoError> {
129
    let Some(name) = RepoName::new(&row.owner, &row.name) else { return Ok(Vec::new()) };
130
    let id = app.repos.read(&name, |r, _| Ok(r.id()?)).await?;
131
    let found: Vec<(i64, String, String, String)> = sqlx::query_as(
132
        "SELECT consumer_id, bookmark, path, heads FROM diffusion_pins WHERE upstream = ? ORDER BY consumer_id, bookmark, path",
133
    )
134
    .bind(hex::encode(id))
135
    .fetch_all(&app.db)
136
    .await
137
    .map_err(|e| crate::repos::RepoError::Io(std::io::Error::other(e)))?;
138
    let mut out = Vec::new();
139
    let mut pinned_sets = Vec::new();
140
    for (consumer_id, bookmark, path, heads) in found {
141
        let Ok(Some(c)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue };
142
        if !roles::allows(roles::role_for(&app.db, account, &c).await.ok().flatten(), crate::auth::Access::Read) {
143
            continue;
144
        }
145
        let pinned: Vec<String> = heads.split('+').filter(|h| !h.is_empty()).map(String::from).collect();
146
        pinned_sets.push(pinned.iter().filter_map(|h| ChangeHash::from_hex(h)).collect::<Vec<_>>());
147
        out.push(Consumer { owner: c.owner, name: c.name, bookmark, path, pinned, behind: None });
148
    }
149
    if out.is_empty() {
150
        return Ok(out);
151
    }
152
    let default = row.default_bookmark.clone();
153
    let behind = app
154
        .repos
155
        .read(&name, move |r, cache| {
156
            let tip = heads_of(r, &default)?;
157
            let tip = cache.summary(r, &tip)?;
158
            Ok(pinned_sets
159
                .iter()
160
                .map(|p| cache.summary(r, p).ok().map(|s| tip.changes.iter().filter(|c| !s.changes.contains(*c)).count()))
161
                .collect::<Vec<_>>())
162
        })
163
        .await?;
164
    for (c, b) in out.iter_mut().zip(behind) {
165
        c.behind = b;
166
    }
167
    Ok(out)
168
}
e7158350 Andy McCall ↶ 169
1d634f69 Andy McCall ↶ 170
/// The bookmark a consumer's bump for the subrepo at `path` lives on.
171
pub fn bump_bookmark(path: &str) -> String {
172
    format!("diffusion/{}", path.trim_matches('/'))
173
}
174
175
/// What a bump did.
176
#[derive(Clone, Debug, PartialEq, Eq)]
177
pub enum Bumped {
178
    /// The bump bookmark now holds the target plus one change moving the pin.
f01cb865 Andy McCall ↶ 179
    Moved { bookmark: String, change: ChangeHash, heads: Vec<ChangeHash>, from: Vec<ChangeHash>, state: String },
1d634f69 Andy McCall ↶ 180
    /// The pin already holds the upstream state.
181
    UpToDate,
182
    /// The bump bookmark already moves the pin to that state.
9aaa88b2 Andy McCall ↶ 183
    Already { from: Vec<ChangeHash>, to: Vec<ChangeHash> },
7a14bdae Andy McCall ↶ 184
    /// The pin names changes the upstream does not hold: not followed.
185
    Unknown,
186
    /// Taking the upstream's state with the pin's own extra changes would
187
    /// conflict.
188
    Conflicts,
1d634f69 Andy McCall ↶ 189
    /// The consumer has no Oxygen pin of that upstream at `path` on its
190
    /// target bookmark.
191
    NoPin,
192
}
193
7a14bdae Andy McCall ↶ 194
/// Where a consumer's pin `old` moves when the upstream reaches `new`,
195
/// worked out in the upstream (§4.3).
196
#[derive(Clone, Debug, PartialEq, Eq)]
197
pub enum Plan {
198
    /// To these heads, which add this many changes.
199
    To(Vec<ChangeHash>, usize),
200
    /// Nothing to add.
201
    UpToDate,
202
    /// The pin names changes the upstream does not hold (rewritten, or
203
    /// from elsewhere): not followed.
204
    Unknown,
205
    /// Taking `new` with the pin's own extra changes would conflict.
206
    Conflicts,
207
}
208
209
/// The pin `old` moved to the upstream's `new`. When the pin has changes
210
/// `new` lacks (say, from an upstream proposal not landed yet), they are
211
/// kept: changes that do not touch each other combine, so the move is to
212
/// both, never dropping what the consumer already relies on.
213
pub async fn plan(app: &Shared, upstream: &RepoName, old: Vec<ChangeHash>, new: Vec<ChangeHash>) -> Result<Plan, crate::repos::RepoError> {
1d634f69 Andy McCall ↶ 214
    app.repos
215
        .read(upstream, move |r, cache| {
7a14bdae Andy McCall ↶ 216
            let Ok(o) = cache.summary(r, &old) else { return Ok(Plan::Unknown) };
217
            let n = cache.summary(r, &new)?;
218
            if o.changes.iter().all(|c| n.changes.contains(c)) {
219
                let added = n.changes.len() - o.changes.len();
220
                return Ok(if added == 0 { Plan::UpToDate } else { Plan::To(new, added) });
221
            }
222
            let mut both = new.clone();
223
            both.extend(old.iter().copied());
224
            let heads = r.load_state(&both)?.heads();
225
            let b = cache.summary(r, &heads)?;
226
            if b.conflicted && !o.conflicted {
227
                return Ok(Plan::Conflicts);
1d634f69 Andy McCall ↶ 228
            }
7a14bdae Andy McCall ↶ 229
            let added = b.changes.len() - o.changes.len();
230
            Ok(if added == 0 { Plan::UpToDate } else { Plan::To(heads, added) })
1d634f69 Andy McCall ↶ 231
        })
232
        .await
233
}
234
235
/// Move `consumer`'s pin of `upstream` at `path` to `new_heads`, on a bump
236
/// bookmark built from `target` (§4.3): one change, signed with the hub's
237
/// key, on the target's heads. The upstream decides forwardness.
238
pub async fn bump(
239
    app: &Shared,
240
    consumer: &RepoRow,
241
    target: &str,
242
    path: &str,
243
    upstream: &RepoRow,
244
    new_heads: Vec<ChangeHash>,
245
) -> Result<Bumped, crate::repos::RepoError> {
246
    use oxy_core::identity::Domain;
247
    use oxy_core::subrepo::Pin;
248
    let (Some(cname), Some(uname)) = (RepoName::new(&consumer.owner, &consumer.name), RepoName::new(&upstream.owner, &upstream.name))
249
    else {
250
        return Ok(Bumped::NoPin);
251
    };
252
    let upstream_id = app.repos.read(&uname, |r, _| Ok(r.id()?)).await?;
253
    // The consumer's current pin at `path` on its target, and on its bump
254
    // bookmark if it has one.
255
    let (t, p) = (target.to_string(), path.trim_matches('/').to_string());
256
    let (current, bumped) = app
257
        .repos
258
        .read(&cname, move |r, cache| {
259
            let pin_on = |bookmark: &str| -> Result<Option<Pin>, crate::repos::RepoError> {
260
                let heads = heads_of(r, bookmark)?;
261
                if heads.is_empty() {
262
                    return Ok(None);
263
                }
264
                let loaded = cache.load(r, &heads)?;
265
                let Some(f) = loaded.snapshot.files.get(&p) else { return Ok(None) };
266
                let oxy_core::state::FileContent::Opaque { blobs } = &f.content else { return Ok(None) };
267
                let Some(b) = blobs.first() else { return Ok(None) };
268
                Ok(Pin::decode(&r.read_blob(b)?).ok())
269
            };
270
            Ok((pin_on(&t)?, pin_on(&bump_bookmark(&p))?))
271
        })
272
        .await?;
273
    let Some(Pin::Oxy { repo, heads: old, bookmark }) = current else { return Ok(Bumped::NoPin) };
7a14bdae Andy McCall ↶ 274
    if repo != upstream_id {
275
        return Ok(Bumped::NoPin);
276
    }
277
    let new_heads = match plan(app, &uname, old.clone(), new_heads.clone()).await? {
278
        Plan::To(heads, _) => heads,
279
        Plan::UpToDate => return Ok(Bumped::UpToDate),
280
        Plan::Unknown => return Ok(Bumped::Unknown),
281
        Plan::Conflicts => return Ok(Bumped::Conflicts),
282
    };
1d634f69 Andy McCall ↶ 283
    if let Some(Pin::Oxy { heads: b, .. }) = &bumped {
284
        let (mut b, mut n) = (b.clone(), new_heads.clone());
285
        b.sort();
286
        n.sort();
287
        if b == n {
9aaa88b2 Andy McCall ↶ 288
            return Ok(Bumped::Already { from: old, to: new_heads });
1d634f69 Andy McCall ↶ 289
        }
290
    }
291
    let (key, secret) =
292
        crate::keys::load_secret(&app.config.keys_dir()).map_err(|e| crate::repos::RepoError::Io(std::io::Error::other(e.to_string())))?;
293
    let identity = app.hub_key.identity.clone();
294
    let upstream_label = format!("{}/{}", upstream.owner, upstream.name);
295
    let (t, p) = (target.to_string(), path.trim_matches('/').to_string());
296
    let pin = Pin::Oxy { repo, heads: new_heads.clone(), bookmark };
a7e6e8e6 Andy McCall ↶ 297
    let old = old.clone();
1d634f69 Andy McCall ↶ 298
    let short: Vec<String> = new_heads.iter().map(|h| h.to_hex()[..12].to_string()).collect();
299
    let message = format!("Diffusion: move {p} to {upstream_label} {}", short.join("+"));
300
    app.repos
301
        .write(&cname, move |r, _| {
302
            let base = heads_of(r, &t)?;
303
            let change = r.build_pin_change(&base, &p, &pin, &message, key)?;
304
            let hash = change.hash();
305
            let sig = secret.sign(Domain::Change, &key, &hash);
306
            let mut state = r.load_state(&base)?;
307
            state.add(change.clone()).map_err(|e| crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(e.to_string())))?;
308
            let mut candidates = base.clone();
309
            candidates.push(hash);
310
            let heads = state.maximal(&candidates);
311
            let bookmark = bump_bookmark(&p);
312
            // The bump bookmark is the hub's own and is rebuilt on the
313
            // target each time, so the bump it replaces may go.
314
            let mut update = r.host_ref_update(&bookmark, &heads, Some((&key, &secret)))?;
315
            update.force = true;
f01cb865 Andy McCall ↶ 316
            let state = update.new_state.to_hex();
1d634f69 Andy McCall ↶ 317
            let report = r.apply_hosted(Some((change, vec![sig])), &[identity], update)?;
318
            if let Some(refused) = report.results.iter().find(|x| !x.ok) {
319
                return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!(
320
                    "the bump was refused: {}",
321
                    refused.reason
322
                ))));
323
            }
f01cb865 Andy McCall ↶ 324
            Ok(Bumped::Moved { bookmark, change: hash, heads, from: old, state })
1d634f69 Andy McCall ↶ 325
        })
326
        .await
327
}
328
a7e6e8e6 Andy McCall ↶ 329
/// The account Diffusion's proposals are opened as.
330
pub const ACCOUNT: &str = "diffusion";
331
332
/// The `diffusion` account, made on first use with no way to sign in.
333
pub async fn account(pool: &Pool) -> Option<Account> {
334
    if let Ok(Some(a)) = db::accounts::account_by_name(pool, ACCOUNT).await {
335
        return Some(a);
336
    }
337
    db::accounts::create_account(pool, ACCOUNT, "diffusion@localhost", "!", "", false).await.ok()
338
}
339
340
/// The upstream changes a bump brings: in `new` and not in `old`, newest
341
/// first, as Markdown lines linking to the upstream's change pages.
342
pub async fn changelog(app: &Shared, upstream: &RepoRow, old: Vec<ChangeHash>, new: Vec<ChangeHash>) -> Vec<String> {
343
    let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { return Vec::new() };
344
    let linked: std::collections::HashMap<String, String> =
345
        db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
346
    let base = format!("/{}/{}", upstream.owner, upstream.name);
347
    app.repos
348
        .read(&name, move |r, cache| {
349
            let (o, n) = (cache.summary(r, &old)?, cache.summary(r, &new)?);
350
            let mut added: Vec<(u64, ChangeHash, String, String)> = Vec::new();
351
            for h in n.changes.iter().filter(|c| !o.changes.contains(*c)) {
352
                let Ok(c) = r.store().get_change(h) else { continue };
353
                let key = c.author.to_hex();
354
                let who = linked.get(&key).cloned().unwrap_or_else(|| key[..12].to_string());
355
                let first = c.message.lines().next().unwrap_or("").trim().to_string();
356
                added.push((c.hlc.wall_ms, *h, first, who));
357
            }
358
            added.sort_by_key(|a| std::cmp::Reverse(a.0));
359
            Ok(added
360
                .into_iter()
361
                .map(|(_, h, msg, who)| {
362
                    format!("- [`{}`]({base}/change/{}) {} ({who})", &h.to_hex()[..12], h.to_hex(), msg.replace('\n', " "))
363
                })
364
                .collect())
365
        })
366
        .await
367
        .unwrap_or_default()
368
}
369
9aaa88b2 Andy McCall ↶ 370
/// Why a bump was made, which its proposal says.
371
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
372
pub enum Why {
373
    /// The upstream's state passed its checks.
374
    Green,
375
    /// The upstream moved (the consumer follows every move).
376
    Moved,
377
    /// The upstream has no checks at all: nothing vouched for it, so the
378
    /// proposal is marked amber, `upstream unverified`.
379
    Unverified,
380
}
381
382
/// Open the bump proposal for `path`'s bump bookmark, or bring the open
383
/// one up to date: into `target`, by the `diffusion` account, labelled
384
/// `dependencies` (and `upstream unverified` while that is so), its body
385
/// the changelog from the pin `from` to `to`. Its number.
a7e6e8e6 Andy McCall ↶ 386
pub async fn propose(
387
    app: &Shared,
388
    consumer: &RepoRow,
389
    target: &str,
390
    path: &str,
391
    upstream: &RepoRow,
9aaa88b2 Andy McCall ↶ 392
    (from, to): (Vec<ChangeHash>, Vec<ChangeHash>),
393
    why: Why,
a7e6e8e6 Andy McCall ↶ 394
) -> Option<i64> {
395
    use crate::db::proposals as pdb;
396
    let bookmark = bump_bookmark(path);
397
    let bookmark = bookmark.as_str();
398
    let me = account(&app.db).await?;
399
    let lines = changelog(app, upstream, from, to.clone()).await;
400
    let slug = format!("{}/{}", upstream.owner, upstream.name);
401
    let short: Vec<String> = to.iter().map(|h| h.to_hex()[..12].to_string()).collect();
1b6536f0 Andy McCall ↶ 402
    let ub = &upstream.default_bookmark;
403
    let count = if lines.len() == 1 { "1 change".to_string() } else { format!("{} changes", lines.len()) };
404
    let title = format!("Diffusion: {path} to {slug} {ub} ({count})");
9aaa88b2 Andy McCall ↶ 405
    let when = match why {
406
        Why::Green => "at its newest state whose checks passed",
407
        Why::Moved => "as it is now",
408
        Why::Unverified => "as it is now",
409
    };
410
    let amber = if why == Why::Unverified {
411
        format!("\n\n> **Upstream unverified.** {slug} has no checks of its own, so nothing has tested this state of it. Only this repository's pipeline tests the move; a later bump from a passing run of {slug} clears this.")
412
    } else {
413
        String::new()
414
    };
a7e6e8e6 Andy McCall ↶ 415
    let body = format!(
9aaa88b2 Andy McCall ↶ 416
        "Moves the subrepo `{path}` to [{slug}](/{slug})'s `{ub}`, {when} (`{}`). Only the pin changes; this repository's own checks test it.{amber}\n\n**What it brings** ({count}):\n\n{}\n\nOpened and kept up to date by Diffusion (docs/diffusion.md). It never lands by itself.",
1b6536f0 Andy McCall ↶ 417
        short.join("+"),
a7e6e8e6 Andy McCall ↶ 418
        lines.join("\n")
419
    );
420
    let open = pdb::list(&app.db, consumer.id, &["open", "draft"]).await.ok()?.into_iter().find(|p| p.source_bookmark == bookmark);
9aaa88b2 Andy McCall ↶ 421
    let (number, id) = match open {
a7e6e8e6 Andy McCall ↶ 422
        Some(p) => {
9aaa88b2 Andy McCall ↶ 423
            if p.title != title || p.body != body {
424
                pdb::edit(&app.db, p.id, &title, &body, target).await.ok()?;
425
                pdb::add_event(&app.db, p.id, ACCOUNT, "updated", &short.join("+")).await.ok();
426
            }
427
            (p.number, p.id)
a7e6e8e6 Andy McCall ↶ 428
        }
429
        None => {
430
            let p = pdb::create(
431
                &app.db,
432
                pdb::NewProposal {
433
                    repo_id: consumer.id,
434
                    title: &title,
435
                    body: &body,
436
                    author_id: Some(me.id),
437
                    author: ACCOUNT,
438
                    draft: false,
439
                    target,
440
                    source_kind: "bookmark",
441
                    source_repo_id: None,
442
                    source_bookmark: bookmark,
443
                    source_changes: "",
444
                },
445
            )
446
            .await
447
            .ok()?;
448
            pdb::add_event(&app.db, p.id, ACCOUNT, "opened", "").await.ok();
449
            db::notify::index(&app.db, "proposal", consumer.id, p.id, p.number, &p.title, &p.body).await.ok();
450
            if let Ok(label) =
451
                db::issues::upsert_label(&app.db, consumer.id, "dependencies", "#0072ff", "A subrepo moves (Diffusion)").await
452
            {
453
                db::issues::set_proposal_label(&app.db, p.id, label.id, true).await.ok();
454
            }
9aaa88b2 Andy McCall ↶ 455
            (p.number, p.id)
a7e6e8e6 Andy McCall ↶ 456
        }
457
    };
9aaa88b2 Andy McCall ↶ 458
    // Amber while the upstream has no checks; cleared by a green bump.
459
    let unverified = db::issues::label_by_name(&app.db, consumer.id, "upstream unverified").await.ok().flatten();
460
    match (why == Why::Unverified, unverified) {
461
        (true, l) => {
462
            let l = match l {
463
                Some(l) => Some(l),
464
                None => db::issues::upsert_label(
465
                    &app.db,
466
                    consumer.id,
467
                    "upstream unverified",
468
                    "#e3a008",
469
                    "The upstream has no checks (Diffusion)",
470
                )
471
                .await
472
                .ok(),
473
            };
474
            if let Some(l) = l {
475
                db::issues::set_proposal_label(&app.db, id, l.id, true).await.ok();
476
            }
477
        }
478
        (false, Some(l)) => {
479
            db::issues::set_proposal_label(&app.db, id, l.id, false).await.ok();
480
        }
481
        (false, None) => {}
482
    }
a7e6e8e6 Andy McCall ↶ 483
    Some(number)
484
}
485
f01cb865 Andy McCall ↶ 486
/// Start a bump's pipeline, as a push of it would. Boxed as `Send`, which
487
/// breaks the cycle between a bump starting runs and a passing run
488
/// starting bumps that the compiler cannot see through.
489
fn start_runs(
490
    app: Shared,
491
    row: RepoRow,
492
    bookmark: String,
493
    state: String,
494
    heads: Vec<ChangeHash>,
495
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
496
    Box::pin(async move { crate::flow::on_push(&app, &row, &bookmark, &state, &heads, ACCOUNT).await })
497
}
498
a7e6e8e6 Andy McCall ↶ 499
/// The text of `.oxymodules` on `bookmark` of `name`, if any.
500
async fn oxymodules(app: &Shared, name: &RepoName, bookmark: &str) -> Option<String> {
501
    let b = bookmark.to_string();
502
    app.repos
503
        .read(name, move |r, cache| {
504
            let heads = heads_of(r, &b)?;
505
            if heads.is_empty() {
506
                return Ok(None);
507
            }
508
            let loaded = cache.load(r, &heads)?;
509
            Ok(match loaded.snapshot.files.get(".oxymodules").map(|f| &f.content) {
510
                Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()),
511
                _ => None,
512
            })
513
        })
514
        .await
515
        .ok()
516
        .flatten()
517
}
518
519
/// The upstream `upstream` reached `heads` on its default bookmark: by a
520
/// push (`green` false) or a passing run of that state (`green` true).
521
/// Bump and propose in every consumer that follows it that way (§4.3).
522
pub async fn propagate(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool) {
3776b70d Andy McCall ↶ 523
    propagate_to(app, upstream, heads, green, None).await
524
}
525
526
/// `propagate`, to one consumer only when `only` names it.
527
async fn propagate_to(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool, only: Option<i64>) {
a7e6e8e6 Andy McCall ↶ 528
    let Some(uname) = RepoName::new(&upstream.owner, &upstream.name) else { return };
529
    let Ok(id) = app.repos.read(&uname, |r, _| Ok(r.id()?)).await else { return };
530
    let rows: Vec<(i64, String, String)> = sqlx::query_as("SELECT consumer_id, bookmark, path FROM diffusion_pins WHERE upstream = ?")
531
        .bind(hex::encode(id))
532
        .fetch_all(&app.db)
533
        .await
534
        .unwrap_or_default();
9aaa88b2 Andy McCall ↶ 535
    let unverified = unverified(app, upstream).await;
a7e6e8e6 Andy McCall ↶ 536
    for (consumer_id, indexed, path) in rows {
3776b70d Andy McCall ↶ 537
        if only.is_some_and(|o| o != consumer_id) {
538
            continue;
539
        }
a7e6e8e6 Andy McCall ↶ 540
        let Ok(Some(consumer)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue };
541
        let Some(cname) = RepoName::new(&consumer.owner, &consumer.name) else { continue };
542
        let learned = target(&app.db, &consumer).await;
543
        let modules = oxymodules(app, &cname, &learned).await;
544
        let r = rule(&app.config.diffusion.follow, &consumer, modules.as_deref(), &path);
545
        let target = r.target.clone().unwrap_or(learned);
546
        if indexed != target {
547
            continue;
548
        }
9aaa88b2 Andy McCall ↶ 549
        // An upstream with no checks never turns green: its moves count
550
        // for green followers too, marked amber (unverified).
a7e6e8e6 Andy McCall ↶ 551
        let go = match r.follow {
552
            Follow::Off => false,
9aaa88b2 Andy McCall ↶ 553
            Follow::Green => green || unverified,
a7e6e8e6 Andy McCall ↶ 554
            Follow::Any => !green,
555
        };
9aaa88b2 Andy McCall ↶ 556
        let why = if green {
557
            Why::Green
558
        } else if unverified {
559
            Why::Unverified
560
        } else {
561
            Why::Moved
562
        };
a7e6e8e6 Andy McCall ↶ 563
        if !go {
564
            continue;
565
        }
566
        match bump(app, &consumer, &target, &path, upstream, heads.clone()).await {
f01cb865 Andy McCall ↶ 567
            Ok(Bumped::Moved { from, bookmark, heads: bumped, state, .. }) => {
568
                // Its pipeline runs as for a push, so the proposal is tested.
569
                tokio::spawn(start_runs(app.clone(), consumer.clone(), bookmark, state, bumped));
9aaa88b2 Andy McCall ↶ 570
                let n = propose(app, &consumer, &target, &path, upstream, (from, heads.clone()), why).await;
a7e6e8e6 Andy McCall ↶ 571
                tracing::info!(
572
                    "diffusion: {}/{} {path} bumped to {}/{} (proposal {n:?})",
573
                    consumer.owner,
574
                    consumer.name,
575
                    upstream.owner,
576
                    upstream.name
577
                );
9aaa88b2 Andy McCall ↶ 578
            }
579
            Ok(Bumped::Already { from, to }) => {
580
                // Already moved: its proposal's text and labels are brought
581
                // up to date all the same.
582
                propose(app, &consumer, &target, &path, upstream, (from, to), why).await;
a7e6e8e6 Andy McCall ↶ 583
            }
7a14bdae Andy McCall ↶ 584
            Ok(other) => tracing::info!("diffusion: {}/{} {path}: no bump ({other:?})", consumer.owner, consumer.name),
a7e6e8e6 Andy McCall ↶ 585
            Err(e) => tracing::warn!("diffusion: bump {}/{} {path}: {e}", consumer.owner, consumer.name),
3776b70d Andy McCall ↶ 586
        }
587
    }
9aaa88b2 Andy McCall ↶ 588
}
589
590
/// Whether `upstream` has no checks of its own: Flow is off for it, or
591
/// its default bookmark has never had a run. Its moves are then
592
/// "unverified" (amber), never green.
593
pub async fn unverified(app: &Shared, upstream: &RepoRow) -> bool {
594
    if !crate::flow::enabled(app, upstream) {
595
        return true;
596
    }
597
    let runs: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM flow_runs WHERE repo_id = ? AND bookmark = ?")
598
        .bind(upstream.id)
599
        .bind(&upstream.default_bookmark)
600
        .fetch_one(&app.db)
601
        .await
602
        .unwrap_or(0);
603
    runs == 0
3776b70d Andy McCall ↶ 604
}
605
606
/// The repository on this hub with Oxygen id `id` (hex).
607
async fn repo_by_oxy_id(app: &Shared, id: &str) -> Option<RepoRow> {
608
    for row in db::repos::list(&app.db).await.ok()? {
609
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
610
        if app.repos.read(&name, |r, _| Ok(r.id()?)).await.ok().map(hex::encode).as_deref() == Some(id) {
611
            return Some(row);
612
        }
613
    }
614
    None
615
}
616
617
/// The newest state of `upstream`'s default bookmark whose run passed.
618
async fn last_green(app: &Shared, upstream: &RepoRow) -> Option<Vec<ChangeHash>> {
619
    let heads: String =
620
        sqlx::query_scalar("SELECT heads FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND status = 'passed' ORDER BY id DESC LIMIT 1")
621
            .bind(upstream.id)
622
            .bind(&upstream.default_bookmark)
623
            .fetch_optional(&app.db)
624
            .await
625
            .ok()
626
            .flatten()?;
627
    let h: Vec<ChangeHash> = heads.split('+').filter_map(ChangeHash::from_hex).collect();
628
    (!h.is_empty()).then_some(h)
629
}
630
631
/// Bring `consumer` up to date with the upstreams it pins, at once: when
632
/// it turns Diffusion on, it is bumped to each upstream's newest state
633
/// that passed (or simply its newest, when it follows every move).
634
pub async fn catch_up(app: &Shared, consumer: &RepoRow) {
635
    let upstreams: Vec<String> = sqlx::query_scalar("SELECT DISTINCT upstream FROM diffusion_pins WHERE consumer_id = ?")
636
        .bind(consumer.id)
637
        .fetch_all(&app.db)
638
        .await
639
        .unwrap_or_default();
640
    for id in upstreams {
641
        let Some(upstream) = repo_by_oxy_id(app, &id).await else { continue };
642
        if let Some(h) = last_green(app, &upstream).await {
643
            propagate_to(app, &upstream, h, true, Some(consumer.id)).await;
644
        }
645
        let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { continue };
646
        let b = upstream.default_bookmark.clone();
647
        if let Ok(h) = app.repos.read(&name, move |r, _| heads_of(r, &b)).await {
648
            propagate_to(app, &upstream, h, false, Some(consumer.id)).await;
a7e6e8e6 Andy McCall ↶ 649
        }
650
    }
651
}
652
e7158350 Andy McCall ↶ 653
/// When a consumer takes an upstream's moves (§4.2).
654
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
655
#[serde(rename_all = "lowercase")]
656
pub enum Follow {
657
    Off,
658
    /// When the upstream state's checks pass.
659
    Green,
660
    /// On every move.
661
    Any,
662
}
663
664
impl Follow {
665
    pub fn parse(s: &str) -> Option<Follow> {
666
        match s.trim() {
667
            "off" => Some(Follow::Off),
668
            "green" => Some(Follow::Green),
669
            "any" => Some(Follow::Any),
670
            _ => None,
671
        }
672
    }
673
}
674
675
/// How one consumer follows one subrepo, from its `.oxymodules` entry, its
676
/// repository setting and the site's default, in that order.
677
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
678
pub struct Rule {
679
    pub follow: Follow,
680
    /// Land a green bump itself (D5); D1 only proposes.
681
    pub land_auto: bool,
682
    /// The bookmark to bump, when `.oxymodules` names one (else learned).
683
    pub target: Option<String>,
684
    /// Paths the consumer watches: upstream changes touching them are
685
    /// flagged in a bump's changelog.
686
    pub watch: Vec<String>,
687
    /// Where `follow` came from: `.oxymodules`, `setting` or `site`.
688
    pub from: &'static str,
689
}
690
691
/// The Diffusion keys of `path`'s entry in `.oxymodules` text: `follow`,
692
/// `land`, `target` and `watch` (comma-separated, or a TOML list).
693
pub fn module_keys(text: &str, path: &str) -> (Option<Follow>, Option<bool>, Option<String>, Vec<String>) {
694
    let (mut follow, mut land, mut target, mut watch) = (None, None, None, Vec::new());
695
    let mut here = false;
696
    for line in text.lines() {
697
        let line = line.trim();
698
        if line.is_empty() || line.starts_with('#') {
699
            continue;
700
        }
701
        if let Some(inner) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
702
            here = inner.trim().trim_matches('"').trim_end_matches('/') == path.trim_end_matches('/');
703
            continue;
704
        }
705
        let (true, Some((k, v))) = (here, line.split_once('=')) else { continue };
706
        let v = v.trim();
707
        let unquoted = v.trim_matches('"').trim();
708
        match k.trim() {
709
            "follow" => follow = Follow::parse(unquoted),
710
            "land" => land = Some(unquoted == "auto"),
711
            "target" if !unquoted.is_empty() => target = Some(unquoted.to_string()),
712
            "watch" => {
713
                watch = v
714
                    .trim_start_matches('[')
715
                    .trim_end_matches(']')
716
                    .split(',')
717
                    .map(|w| w.trim().trim_matches('"').trim().to_string())
718
                    .filter(|w| !w.is_empty())
719
                    .collect()
720
            }
721
            _ => {}
722
        }
723
    }
724
    (follow, land, target, watch)
725
}
726
727
/// How `row` follows its subrepo at `path`, given its `.oxymodules` text.
728
pub fn rule(site_default: &str, row: &RepoRow, oxymodules: Option<&str>, path: &str) -> Rule {
729
    let (follow, land, target, watch) = oxymodules.map(|t| module_keys(t, path)).unwrap_or_default();
730
    let (follow, from) = match follow {
731
        Some(f) => (f, ".oxymodules"),
732
        None => match Follow::parse(&row.diffusion) {
733
            Some(f) => (f, "setting"),
734
            None => (Follow::parse(site_default).unwrap_or(Follow::Off), "site"),
735
        },
736
    };
737
    Rule { follow, land_auto: land.unwrap_or(false), target, watch, from }
738
}
739
740
#[cfg(test)]
741
mod tests {
742
    use super::*;
743
744
    const MODULES: &str = r#"
745
[rstar-api]
746
url = https://oxygenhub.io/doomsdayone/rstar-api
747
follow = green
748
land = "propose"
749
target = develop
750
watch = ["src/x16/irq*", "src/x16/frame*"]
751
752
[other]
753
url = https://example/other
754
follow = any
755
"#;
756
757
    fn row(diffusion: &str) -> RepoRow {
758
        RepoRow {
759
            id: 1,
760
            owner: "o".into(),
761
            name: "n".into(),
762
            description: String::new(),
763
            default_bookmark: "main".into(),
764
            visibility: "public".into(),
765
            created_ms: 0,
766
            updated_ms: 0,
767
            git_mirror: false,
768
            git_mirror_state: String::new(),
769
            forked_from: None,
770
            topics: String::new(),
771
            flow: String::new(),
772
            diffusion: diffusion.into(),
773
            ..Default::default()
774
        }
775
    }
776
777
    #[test]
778
    fn oxymodules_keys_are_read_per_entry() {
779
        let (f, land, target, watch) = module_keys(MODULES, "rstar-api");
780
        assert_eq!((f, land, target.as_deref()), (Some(Follow::Green), Some(false), Some("develop")));
781
        assert_eq!(watch, vec!["src/x16/irq*", "src/x16/frame*"]);
782
        assert_eq!(module_keys(MODULES, "other").0, Some(Follow::Any));
783
        assert_eq!(module_keys(MODULES, "missing"), (None, None, None, vec![]));
784
        assert_eq!(module_keys("[a]\nwatch = x, y\n", "a").3, vec!["x", "y"]);
785
    }
786
787
    #[test]
788
    fn oxymodules_wins_then_the_setting_then_the_site() {
789
        let r = rule("off", &row("any"), Some(MODULES), "rstar-api");
790
        assert_eq!((r.follow, r.from), (Follow::Green, ".oxymodules"));
791
        let r = rule("off", &row("any"), Some("[rstar-api]\nurl = x\n"), "rstar-api");
792
        assert_eq!((r.follow, r.from), (Follow::Any, "setting"));
793
        let r = rule("green", &row(""), None, "rstar-api");
794
        assert_eq!((r.follow, r.from), (Follow::Green, "site"));
795
        assert_eq!(rule("nonsense", &row(""), None, "x").follow, Follow::Off);
796
    }
797
}