OXYGENHUB
# 7a14bdaeb857 oxygenhub / crates / hub / src / diffusion.rs
29.1 KiB · Rust · last changed Diffusion: keep a pin's own changes when moving it 24 days ago source blame history raw
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
}
169
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.
179
    Moved { bookmark: String, change: ChangeHash, heads: Vec<ChangeHash>, from: Vec<ChangeHash> },
180
    /// The pin already holds the upstream state.
181
    UpToDate,
182
    /// The bump bookmark already moves the pin to that state.
183
    Already,
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,
189
    /// The consumer has no Oxygen pin of that upstream at `path` on its
190
    /// target bookmark.
191
    NoPin,
192
}
193
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> {
214
    app.repos
215
        .read(upstream, move |r, cache| {
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);
228
            }
229
            let added = b.changes.len() - o.changes.len();
230
            Ok(if added == 0 { Plan::UpToDate } else { Plan::To(heads, added) })
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) };
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
    };
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 {
288
            return Ok(Bumped::Already);
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 };
297
    let old = old.clone();
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;
316
            let report = r.apply_hosted(Some((change, vec![sig])), &[identity], update)?;
317
            if let Some(refused) = report.results.iter().find(|x| !x.ok) {
318
                return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!(
319
                    "the bump was refused: {}",
320
                    refused.reason
321
                ))));
322
            }
323
            Ok(Bumped::Moved { bookmark, change: hash, heads, from: old })
324
        })
325
        .await
326
}
327
328
/// The account Diffusion's proposals are opened as.
329
pub const ACCOUNT: &str = "diffusion";
330
331
/// The `diffusion` account, made on first use with no way to sign in.
332
pub async fn account(pool: &Pool) -> Option<Account> {
333
    if let Ok(Some(a)) = db::accounts::account_by_name(pool, ACCOUNT).await {
334
        return Some(a);
335
    }
336
    db::accounts::create_account(pool, ACCOUNT, "diffusion@localhost", "!", "", false).await.ok()
337
}
338
339
/// The upstream changes a bump brings: in `new` and not in `old`, newest
340
/// first, as Markdown lines linking to the upstream's change pages.
341
pub async fn changelog(app: &Shared, upstream: &RepoRow, old: Vec<ChangeHash>, new: Vec<ChangeHash>) -> Vec<String> {
342
    let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { return Vec::new() };
343
    let linked: std::collections::HashMap<String, String> =
344
        db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
345
    let base = format!("/{}/{}", upstream.owner, upstream.name);
346
    app.repos
347
        .read(&name, move |r, cache| {
348
            let (o, n) = (cache.summary(r, &old)?, cache.summary(r, &new)?);
349
            let mut added: Vec<(u64, ChangeHash, String, String)> = Vec::new();
350
            for h in n.changes.iter().filter(|c| !o.changes.contains(*c)) {
351
                let Ok(c) = r.store().get_change(h) else { continue };
352
                let key = c.author.to_hex();
353
                let who = linked.get(&key).cloned().unwrap_or_else(|| key[..12].to_string());
354
                let first = c.message.lines().next().unwrap_or("").trim().to_string();
355
                added.push((c.hlc.wall_ms, *h, first, who));
356
            }
357
            added.sort_by_key(|a| std::cmp::Reverse(a.0));
358
            Ok(added
359
                .into_iter()
360
                .map(|(_, h, msg, who)| {
361
                    format!("- [`{}`]({base}/change/{}) {} ({who})", &h.to_hex()[..12], h.to_hex(), msg.replace('\n', " "))
362
                })
363
                .collect())
364
        })
365
        .await
366
        .unwrap_or_default()
367
}
368
369
/// Open the bump proposal for `bookmark`, or bring the open one up to
370
/// date: from `bookmark` into `target`, by the `diffusion` account,
371
/// labelled `dependencies`, its body the changelog. Its number.
372
pub async fn propose(
373
    app: &Shared,
374
    consumer: &RepoRow,
375
    target: &str,
376
    path: &str,
377
    upstream: &RepoRow,
378
    from: Vec<ChangeHash>,
379
    to: Vec<ChangeHash>,
380
) -> Option<i64> {
381
    use crate::db::proposals as pdb;
382
    let bookmark = bump_bookmark(path);
383
    let bookmark = bookmark.as_str();
384
    let me = account(&app.db).await?;
385
    let lines = changelog(app, upstream, from, to.clone()).await;
386
    let slug = format!("{}/{}", upstream.owner, upstream.name);
387
    let short: Vec<String> = to.iter().map(|h| h.to_hex()[..12].to_string()).collect();
388
    let title = format!(
389
        "Diffusion: {path} to {slug} {} ({})",
390
        short.join("+"),
391
        if lines.len() == 1 { "1 change".into() } else { format!("{} changes", lines.len()) }
392
    );
393
    let body = format!(
394
        "Moves the subrepo `{path}` to the newest state of [{slug}](/{slug}) that {}. Only the pin changes; this repository's own checks test it.\n\n**What it brings** ({} change{}):\n\n{}\n\nOpened and kept up to date by Diffusion (docs/diffusion.md). It never lands by itself.",
395
        if Follow::parse(&consumer.diffusion) == Some(Follow::Any) { "moved" } else { "passed its checks" },
396
        lines.len(),
397
        if lines.len() == 1 { "" } else { "s" },
398
        lines.join("\n")
399
    );
400
    let open = pdb::list(&app.db, consumer.id, &["open", "draft"]).await.ok()?.into_iter().find(|p| p.source_bookmark == bookmark);
401
    let number = match open {
402
        Some(p) => {
403
            pdb::edit(&app.db, p.id, &title, &body, target).await.ok()?;
404
            pdb::add_event(&app.db, p.id, ACCOUNT, "updated", &short.join("+")).await.ok();
405
            p.number
406
        }
407
        None => {
408
            let p = pdb::create(
409
                &app.db,
410
                pdb::NewProposal {
411
                    repo_id: consumer.id,
412
                    title: &title,
413
                    body: &body,
414
                    author_id: Some(me.id),
415
                    author: ACCOUNT,
416
                    draft: false,
417
                    target,
418
                    source_kind: "bookmark",
419
                    source_repo_id: None,
420
                    source_bookmark: bookmark,
421
                    source_changes: "",
422
                },
423
            )
424
            .await
425
            .ok()?;
426
            pdb::add_event(&app.db, p.id, ACCOUNT, "opened", "").await.ok();
427
            db::notify::index(&app.db, "proposal", consumer.id, p.id, p.number, &p.title, &p.body).await.ok();
428
            if let Ok(label) =
429
                db::issues::upsert_label(&app.db, consumer.id, "dependencies", "#0072ff", "A subrepo moves (Diffusion)").await
430
            {
431
                db::issues::set_proposal_label(&app.db, p.id, label.id, true).await.ok();
432
            }
433
            p.number
434
        }
435
    };
436
    Some(number)
437
}
438
439
/// The text of `.oxymodules` on `bookmark` of `name`, if any.
440
async fn oxymodules(app: &Shared, name: &RepoName, bookmark: &str) -> Option<String> {
441
    let b = bookmark.to_string();
442
    app.repos
443
        .read(name, move |r, cache| {
444
            let heads = heads_of(r, &b)?;
445
            if heads.is_empty() {
446
                return Ok(None);
447
            }
448
            let loaded = cache.load(r, &heads)?;
449
            Ok(match loaded.snapshot.files.get(".oxymodules").map(|f| &f.content) {
450
                Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()),
451
                _ => None,
452
            })
453
        })
454
        .await
455
        .ok()
456
        .flatten()
457
}
458
459
/// The upstream `upstream` reached `heads` on its default bookmark: by a
460
/// push (`green` false) or a passing run of that state (`green` true).
461
/// Bump and propose in every consumer that follows it that way (§4.3).
462
pub async fn propagate(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool) {
463
    propagate_to(app, upstream, heads, green, None).await
464
}
465
466
/// `propagate`, to one consumer only when `only` names it.
467
async fn propagate_to(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool, only: Option<i64>) {
468
    let Some(uname) = RepoName::new(&upstream.owner, &upstream.name) else { return };
469
    let Ok(id) = app.repos.read(&uname, |r, _| Ok(r.id()?)).await else { return };
470
    let rows: Vec<(i64, String, String)> = sqlx::query_as("SELECT consumer_id, bookmark, path FROM diffusion_pins WHERE upstream = ?")
471
        .bind(hex::encode(id))
472
        .fetch_all(&app.db)
473
        .await
474
        .unwrap_or_default();
475
    for (consumer_id, indexed, path) in rows {
476
        if only.is_some_and(|o| o != consumer_id) {
477
            continue;
478
        }
479
        let Ok(Some(consumer)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue };
480
        let Some(cname) = RepoName::new(&consumer.owner, &consumer.name) else { continue };
481
        let learned = target(&app.db, &consumer).await;
482
        let modules = oxymodules(app, &cname, &learned).await;
483
        let r = rule(&app.config.diffusion.follow, &consumer, modules.as_deref(), &path);
484
        let target = r.target.clone().unwrap_or(learned);
485
        if indexed != target {
486
            continue;
487
        }
488
        let go = match r.follow {
489
            Follow::Off => false,
490
            Follow::Green => green,
491
            Follow::Any => !green,
492
        };
493
        if !go {
494
            continue;
495
        }
496
        match bump(app, &consumer, &target, &path, upstream, heads.clone()).await {
497
            Ok(Bumped::Moved { from, .. }) => {
498
                let n = propose(app, &consumer, &target, &path, upstream, from, heads.clone()).await;
499
                tracing::info!(
500
                    "diffusion: {}/{} {path} bumped to {}/{} (proposal {n:?})",
501
                    consumer.owner,
502
                    consumer.name,
503
                    upstream.owner,
504
                    upstream.name
505
                );
506
            }
507
            Ok(other) => tracing::info!("diffusion: {}/{} {path}: no bump ({other:?})", consumer.owner, consumer.name),
508
            Err(e) => tracing::warn!("diffusion: bump {}/{} {path}: {e}", consumer.owner, consumer.name),
509
        }
510
    }
511
}
512
513
/// The repository on this hub with Oxygen id `id` (hex).
514
async fn repo_by_oxy_id(app: &Shared, id: &str) -> Option<RepoRow> {
515
    for row in db::repos::list(&app.db).await.ok()? {
516
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
517
        if app.repos.read(&name, |r, _| Ok(r.id()?)).await.ok().map(hex::encode).as_deref() == Some(id) {
518
            return Some(row);
519
        }
520
    }
521
    None
522
}
523
524
/// The newest state of `upstream`'s default bookmark whose run passed.
525
async fn last_green(app: &Shared, upstream: &RepoRow) -> Option<Vec<ChangeHash>> {
526
    let heads: String =
527
        sqlx::query_scalar("SELECT heads FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND status = 'passed' ORDER BY id DESC LIMIT 1")
528
            .bind(upstream.id)
529
            .bind(&upstream.default_bookmark)
530
            .fetch_optional(&app.db)
531
            .await
532
            .ok()
533
            .flatten()?;
534
    let h: Vec<ChangeHash> = heads.split('+').filter_map(ChangeHash::from_hex).collect();
535
    (!h.is_empty()).then_some(h)
536
}
537
538
/// Bring `consumer` up to date with the upstreams it pins, at once: when
539
/// it turns Diffusion on, it is bumped to each upstream's newest state
540
/// that passed (or simply its newest, when it follows every move).
541
pub async fn catch_up(app: &Shared, consumer: &RepoRow) {
542
    let upstreams: Vec<String> = sqlx::query_scalar("SELECT DISTINCT upstream FROM diffusion_pins WHERE consumer_id = ?")
543
        .bind(consumer.id)
544
        .fetch_all(&app.db)
545
        .await
546
        .unwrap_or_default();
547
    for id in upstreams {
548
        let Some(upstream) = repo_by_oxy_id(app, &id).await else { continue };
549
        if let Some(h) = last_green(app, &upstream).await {
550
            propagate_to(app, &upstream, h, true, Some(consumer.id)).await;
551
        }
552
        let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { continue };
553
        let b = upstream.default_bookmark.clone();
554
        if let Ok(h) = app.repos.read(&name, move |r, _| heads_of(r, &b)).await {
555
            propagate_to(app, &upstream, h, false, Some(consumer.id)).await;
556
        }
557
    }
558
}
559
560
/// When a consumer takes an upstream's moves (§4.2).
561
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
562
#[serde(rename_all = "lowercase")]
563
pub enum Follow {
564
    Off,
565
    /// When the upstream state's checks pass.
566
    Green,
567
    /// On every move.
568
    Any,
569
}
570
571
impl Follow {
572
    pub fn parse(s: &str) -> Option<Follow> {
573
        match s.trim() {
574
            "off" => Some(Follow::Off),
575
            "green" => Some(Follow::Green),
576
            "any" => Some(Follow::Any),
577
            _ => None,
578
        }
579
    }
580
}
581
582
/// How one consumer follows one subrepo, from its `.oxymodules` entry, its
583
/// repository setting and the site's default, in that order.
584
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
585
pub struct Rule {
586
    pub follow: Follow,
587
    /// Land a green bump itself (D5); D1 only proposes.
588
    pub land_auto: bool,
589
    /// The bookmark to bump, when `.oxymodules` names one (else learned).
590
    pub target: Option<String>,
591
    /// Paths the consumer watches: upstream changes touching them are
592
    /// flagged in a bump's changelog.
593
    pub watch: Vec<String>,
594
    /// Where `follow` came from: `.oxymodules`, `setting` or `site`.
595
    pub from: &'static str,
596
}
597
598
/// The Diffusion keys of `path`'s entry in `.oxymodules` text: `follow`,
599
/// `land`, `target` and `watch` (comma-separated, or a TOML list).
600
pub fn module_keys(text: &str, path: &str) -> (Option<Follow>, Option<bool>, Option<String>, Vec<String>) {
601
    let (mut follow, mut land, mut target, mut watch) = (None, None, None, Vec::new());
602
    let mut here = false;
603
    for line in text.lines() {
604
        let line = line.trim();
605
        if line.is_empty() || line.starts_with('#') {
606
            continue;
607
        }
608
        if let Some(inner) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
609
            here = inner.trim().trim_matches('"').trim_end_matches('/') == path.trim_end_matches('/');
610
            continue;
611
        }
612
        let (true, Some((k, v))) = (here, line.split_once('=')) else { continue };
613
        let v = v.trim();
614
        let unquoted = v.trim_matches('"').trim();
615
        match k.trim() {
616
            "follow" => follow = Follow::parse(unquoted),
617
            "land" => land = Some(unquoted == "auto"),
618
            "target" if !unquoted.is_empty() => target = Some(unquoted.to_string()),
619
            "watch" => {
620
                watch = v
621
                    .trim_start_matches('[')
622
                    .trim_end_matches(']')
623
                    .split(',')
624
                    .map(|w| w.trim().trim_matches('"').trim().to_string())
625
                    .filter(|w| !w.is_empty())
626
                    .collect()
627
            }
628
            _ => {}
629
        }
630
    }
631
    (follow, land, target, watch)
632
}
633
634
/// How `row` follows its subrepo at `path`, given its `.oxymodules` text.
635
pub fn rule(site_default: &str, row: &RepoRow, oxymodules: Option<&str>, path: &str) -> Rule {
636
    let (follow, land, target, watch) = oxymodules.map(|t| module_keys(t, path)).unwrap_or_default();
637
    let (follow, from) = match follow {
638
        Some(f) => (f, ".oxymodules"),
639
        None => match Follow::parse(&row.diffusion) {
640
            Some(f) => (f, "setting"),
641
            None => (Follow::parse(site_default).unwrap_or(Follow::Off), "site"),
642
        },
643
    };
644
    Rule { follow, land_auto: land.unwrap_or(false), target, watch, from }
645
}
646
647
#[cfg(test)]
648
mod tests {
649
    use super::*;
650
651
    const MODULES: &str = r#"
652
[rstar-api]
653
url = https://oxygenhub.io/doomsdayone/rstar-api
654
follow = green
655
land = "propose"
656
target = develop
657
watch = ["src/x16/irq*", "src/x16/frame*"]
658
659
[other]
660
url = https://example/other
661
follow = any
662
"#;
663
664
    fn row(diffusion: &str) -> RepoRow {
665
        RepoRow {
666
            id: 1,
667
            owner: "o".into(),
668
            name: "n".into(),
669
            description: String::new(),
670
            default_bookmark: "main".into(),
671
            visibility: "public".into(),
672
            created_ms: 0,
673
            updated_ms: 0,
674
            git_mirror: false,
675
            git_mirror_state: String::new(),
676
            forked_from: None,
677
            topics: String::new(),
678
            flow: String::new(),
679
            diffusion: diffusion.into(),
680
            ..Default::default()
681
        }
682
    }
683
684
    #[test]
685
    fn oxymodules_keys_are_read_per_entry() {
686
        let (f, land, target, watch) = module_keys(MODULES, "rstar-api");
687
        assert_eq!((f, land, target.as_deref()), (Some(Follow::Green), Some(false), Some("develop")));
688
        assert_eq!(watch, vec!["src/x16/irq*", "src/x16/frame*"]);
689
        assert_eq!(module_keys(MODULES, "other").0, Some(Follow::Any));
690
        assert_eq!(module_keys(MODULES, "missing"), (None, None, None, vec![]));
691
        assert_eq!(module_keys("[a]\nwatch = x, y\n", "a").3, vec!["x", "y"]);
692
    }
693
694
    #[test]
695
    fn oxymodules_wins_then_the_setting_then_the_site() {
696
        let r = rule("off", &row("any"), Some(MODULES), "rstar-api");
697
        assert_eq!((r.follow, r.from), (Follow::Green, ".oxymodules"));
698
        let r = rule("off", &row("any"), Some("[rstar-api]\nurl = x\n"), "rstar-api");
699
        assert_eq!((r.follow, r.from), (Follow::Any, "setting"));
700
        let r = rule("green", &row(""), None, "rstar-api");
701
        assert_eq!((r.follow, r.from), (Follow::Green, "site"));
702
        assert_eq!(rule("nonsense", &row(""), None, "x").follow, Follow::Off);
703
    }
704
}