OXYGENHUB
# 5d54cf746e00 oxygenhub / crates / hub / src / diffusion.rs
45.4 KiB · Rust · last changed Diffusion index writes log every failure and try once more 20 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
    // A failure is logged and tried once more after a moment (oxygenhub#210):
52
    // an index left behind shows a consumer behind with no bump.
53
    let repo = format!("{}/{}", row.owner, row.name);
54
    for attempt in 1..=2 {
55
        match try_record(app, row, bookmark, heads).await {
56
            Ok(()) => {
57
                if attempt > 1 {
58
                    tracing::info!("diffusion: indexed {repo} {bookmark} on the second try");
59
                }
60
                return;
61
            }
62
            Err(why) if attempt == 1 => {
63
                tracing::warn!("diffusion: indexing {repo} {bookmark} failed ({why}); trying again");
64
                tokio::time::sleep(RETRY_AFTER).await;
65
            }
66
            Err(why) => {
67
                FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
68
                tracing::error!("diffusion: indexing {repo} {bookmark} failed again ({why}); its pins stay as they were");
69
            }
70
        }
71
    }
72
}
73
74
/// How long [`record`] waits before its second try.
75
const RETRY_AFTER: std::time::Duration = std::time::Duration::from_millis(250);
76
77
/// Indexing failures that the retry did not mend, since the hub started.
78
pub static FAILURES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
79
80
/// Failures to force, per repository (tests only: [`fail_next_records`]).
81
static FORCED: std::sync::Mutex<Option<std::collections::HashMap<String, u32>>> = std::sync::Mutex::new(None);
82
83
/// Make the next `n` index writes for a repository fail, as a busy
84
/// database would (for tests of the retry).
85
#[doc(hidden)]
86
pub fn fail_next_records(app: &Shared, repo_id: i64, n: u32) {
87
    FORCED.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(Default::default).insert(key(app, repo_id), n);
88
}
89
90
/// Forced failures not yet used (tests only).
91
#[doc(hidden)]
92
pub fn forced_left(app: &Shared, repo_id: i64) -> u32 {
93
    FORCED.lock().unwrap_or_else(|p| p.into_inner()).as_ref().and_then(|m| m.get(&key(app, repo_id)).copied()).unwrap_or(0)
94
}
95
96
fn forced(app: &Shared, repo_id: i64) -> bool {
97
    let mut forced = FORCED.lock().unwrap_or_else(|p| p.into_inner());
98
    match forced.as_mut().and_then(|m| m.get_mut(&key(app, repo_id))) {
99
        Some(n) if *n > 0 => {
100
            *n -= 1;
101
            true
102
        }
103
        _ => false,
104
    }
105
}
106
107
/// One try at replacing a bookmark's indexed pins; which step failed and
108
/// why. A state that cannot be read leaves the index as it was rather than
109
/// emptying it.
110
async fn try_record(app: &Shared, row: &RepoRow, bookmark: &str, heads: &[ChangeHash]) -> Result<(), String> {
111
    let Some(name) = RepoName::new(&row.owner, &row.name) else { return Ok(()) };
112
    let pins = if heads.is_empty() {
113
        Vec::new()
114
    } else {
115
        crate::flow::pins_in(app, name, heads.to_vec()).await.map_err(|e| format!("reading the pins: {e}"))?
116
    };
117
    let now = db::now_ms();
118
    // The upstream's repository on this hub, when it is one.
119
    let mut upstreams = Vec::new();
120
    for (_, id, _) in &pins {
121
        upstreams.push(repo_by_oxy_id(app, &hex::encode(id)).await.map(|r| r.id));
122
    }
123
    if forced(app, row.id) {
124
        return Err("begin: forced for a test".into());
125
    }
126
    let mut tx = app.db.begin().await.map_err(|e| format!("begin: {e}"))?;
127
    sqlx::query("DELETE FROM diffusion_pins WHERE consumer_id = ? AND bookmark = ?")
128
        .bind(row.id)
129
        .bind(bookmark)
130
        .execute(&mut *tx)
131
        .await
132
        .map_err(|e| format!("delete: {e}"))?;
133
    for ((path, id, pinned), upstream_row) in pins.iter().zip(&upstreams) {
134
        let heads: Vec<String> = pinned.iter().map(|h| h.to_hex()).collect();
135
        sqlx::query(
136
            "INSERT INTO diffusion_pins (consumer_id, bookmark, path, upstream, heads, updated_ms, upstream_repo_id) VALUES (?, ?, ?, ?, ?, ?, ?)",
137
        )
138
        .bind(row.id)
139
        .bind(bookmark)
140
        .bind(path)
141
        .bind(hex::encode(id))
142
        .bind(heads.join("+"))
143
        .bind(now)
144
        .bind(upstream_row)
145
        .execute(&mut *tx)
146
        .await
147
        .map_err(|e| format!("insert {path}: {e}"))?;
148
    }
149
    tx.commit().await.map_err(|e| format!("commit: {e}"))?;
150
    for u in upstreams.iter().flatten() {
151
        mark(app, row.id);
152
        mark(app, *u);
153
    }
154
    Ok(())
155
}
156
157
/// After a push: index the pins of each moved bookmark that is followed.
158
pub async fn after_push(app: &Shared, row: &RepoRow, moved: &[(String, String, Vec<ChangeHash>)]) {
159
    let followed = followed_bookmarks(&app.db, row).await;
160
    for (bookmark, _, heads) in moved {
161
        if followed.contains(bookmark) {
162
            record(app, row, bookmark, heads).await;
163
        }
164
    }
165
}
166
167
static INVOLVED: std::sync::Mutex<Option<std::collections::HashSet<String>>> = std::sync::Mutex::new(None);
168
169
fn key(app: &Shared, repo_id: i64) -> String {
170
    format!("{}#{repo_id}", app.repos.root().display())
171
}
172
173
fn mark(app: &Shared, repo_id: i64) {
174
    INVOLVED.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(Default::default).insert(key(app, repo_id));
175
}
176
177
/// Whether a repository takes part in Diffusion, as an upstream or a
178
/// consumer on this hub: its Diffusion tab shows (#150).
179
pub fn involved(app: &Shared, repo_id: i64) -> bool {
180
    INVOLVED.lock().unwrap_or_else(|p| p.into_inner()).as_ref().is_some_and(|s| s.contains(&key(app, repo_id)))
181
}
182
183
/// Index every repository's followed bookmarks, for a hub that had no
184
/// index before (run once at start, in the background).
185
pub async fn backfill(app: &Shared) {
186
    let Ok(rows) = db::repos::list(&app.db).await else { return };
187
    for row in rows {
188
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
189
        for bookmark in followed_bookmarks(&app.db, &row).await {
190
            let b = bookmark.clone();
191
            let heads = app.repos.read(&name, move |r, _| heads_of(r, &b)).await;
192
            if let Ok(heads) = heads {
193
                record(app, &row, &bookmark, &heads).await;
194
            }
195
        }
196
    }
197
}
198
199
/// A bookmark's heads as the repository has them now (not a cached
200
/// list, which a push refreshes a moment later); empty when it has none.
201
fn heads_of(r: &oxy_core::repo::Repo, bookmark: &str) -> Result<Vec<ChangeHash>, crate::repos::RepoError> {
202
    Ok(r.bookmarks()?.into_iter().find(|b| b.name == bookmark).map(|b| b.heads).unwrap_or_default())
203
}
204
205
/// One consumer of an upstream, as an upstream's page and API show it.
206
#[derive(Clone, Debug, Serialize)]
207
pub struct Consumer {
208
    pub owner: String,
209
    pub name: String,
210
    pub bookmark: String,
211
    pub path: String,
212
    /// The upstream heads it pins, hex.
213
    pub pinned: Vec<String>,
214
    /// Upstream changes on its default bookmark the pin lacks; `None` when
215
    /// the hub cannot tell (the pinned changes are not in the upstream).
216
    pub behind: Option<usize>,
217
    /// How it follows the upstream (from its setting, or the site's).
218
    pub follow: Follow,
219
    /// Its open bump proposal's number, if it has one.
220
    pub bump: Option<i64>,
221
    /// The newest run of its bump bookmark: number and status.
222
    pub run: Option<(i64, String)>,
223
    /// Its last landed bump: number and when.
224
    pub landed: Option<(i64, i64)>,
225
    /// What the views show (#150).
226
    pub colour: Colour,
227
}
228
229
/// A consumer's Diffusion status at a glance (#150, Andy's colours):
230
/// green when the upstream was checked and the consumer's run on the bump
231
/// passed; amber when the run passed but the upstream has no checks; red
232
/// when the run failed; grey while it runs; up to date when there is
233
/// nothing to bump; off when it does not follow.
234
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
235
#[serde(rename_all = "kebab-case")]
236
pub enum Colour {
237
    Green,
238
    Amber,
239
    Red,
240
    Grey,
241
    UpToDate,
242
    Off,
243
}
244
245
impl Colour {
246
    pub fn class(&self) -> &'static str {
247
        match self {
248
            Colour::Green => "df-green",
249
            Colour::Amber => "df-amber",
250
            Colour::Red => "df-red",
251
            Colour::Grey => "df-grey",
252
            Colour::UpToDate => "df-current",
253
            Colour::Off => "df-off",
254
        }
255
    }
256
257
    pub fn label(&self) -> &'static str {
258
        match self {
259
            Colour::Green => "green",
260
            Colour::Amber => "amber: upstream unverified",
261
            Colour::Red => "red: its run failed",
262
            Colour::Grey => "testing",
263
            Colour::UpToDate => "up to date",
264
            Colour::Off => "not following",
265
        }
266
    }
267
268
    /// The colour from what is known of a consumer.
269
    pub fn of(follow: Follow, behind: Option<usize>, bump: Option<i64>, run: Option<&str>, unverified: bool) -> Colour {
270
        if follow == Follow::Off {
271
            return Colour::Off;
272
        }
273
        match (bump, run) {
274
            (Some(_), Some("passed")) if unverified => Colour::Amber,
275
            (Some(_), Some("passed")) => Colour::Green,
276
            (Some(_), Some("failed" | "error" | "cancelled")) => Colour::Red,
277
            (Some(_), _) => Colour::Grey,
278
            (None, _) if behind == Some(0) => Colour::UpToDate,
279
            (None, _) => Colour::Grey,
280
        }
281
    }
282
}
283
284
/// The consumers of `row` that `account` may read, with how far behind
285
/// the upstream's default bookmark each pin is.
286
pub async fn consumers(app: &Shared, row: &RepoRow, account: Option<&Account>) -> Result<Vec<Consumer>, crate::repos::RepoError> {
287
    let Some(name) = RepoName::new(&row.owner, &row.name) else { return Ok(Vec::new()) };
288
    let id = app.repos.read(&name, |r, _| Ok(r.id()?)).await?;
289
    let found: Vec<(i64, String, String, String)> = sqlx::query_as(
290
        "SELECT consumer_id, bookmark, path, heads FROM diffusion_pins WHERE upstream = ? ORDER BY consumer_id, bookmark, path",
291
    )
292
    .bind(hex::encode(id))
293
    .fetch_all(&app.db)
294
    .await
295
    .map_err(|e| crate::repos::RepoError::Io(std::io::Error::other(e)))?;
296
    let mut out = Vec::new();
297
    let mut pinned_sets = Vec::new();
298
    let unverified = unverified(app, row).await;
299
    for (consumer_id, bookmark, path, heads) in found {
300
        let Ok(Some(c)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue };
301
        if !roles::allows(roles::role_for(&app.db, account, &c).await.ok().flatten(), crate::auth::Access::Read) {
302
            continue;
303
        }
304
        // One row per consumer and subrepo: the bookmark its work lands on.
305
        if bookmark != target(&app.db, &c).await {
306
            continue;
307
        }
308
        let pinned: Vec<String> = heads.split('+').filter(|h| !h.is_empty()).map(String::from).collect();
309
        pinned_sets.push(pinned.iter().filter_map(|h| ChangeHash::from_hex(h)).collect::<Vec<_>>());
310
        let bump_bm = bump_bookmark(&path);
311
        let mine: Vec<db::proposals::ProposalRow> = db::proposals::list(&app.db, c.id, &[])
312
            .await
313
            .unwrap_or_default()
314
            .into_iter()
315
            .filter(|p| p.source_bookmark == bump_bm)
316
            .collect();
317
        let bump = mine.iter().find(|p| p.state == "open" || p.state == "draft").map(|p| p.number);
318
        let landed = mine.iter().filter(|p| p.state == "landed").max_by_key(|p| p.landed_ms).map(|p| (p.number, p.landed_ms));
319
        let run: Option<(i64, String)> =
320
            sqlx::query_as("SELECT number, status FROM flow_runs WHERE repo_id = ? AND bookmark = ? ORDER BY id DESC LIMIT 1")
321
                .bind(c.id)
322
                .bind(&bump_bm)
323
                .fetch_optional(&app.db)
324
                .await
325
                .ok()
326
                .flatten();
327
        let follow = rule(&app.config.diffusion.follow, &c, None, &path).follow;
328
        out.push(Consumer {
329
            owner: c.owner,
330
            name: c.name,
331
            bookmark,
332
            path,
333
            pinned,
334
            behind: None,
335
            follow,
336
            bump,
337
            run,
338
            landed,
339
            colour: Colour::Off,
340
        });
341
    }
342
    if out.is_empty() {
343
        return Ok(out);
344
    }
345
    let default = row.default_bookmark.clone();
346
    let behind = app
347
        .repos
348
        .read(&name, move |r, cache| {
349
            let tip = heads_of(r, &default)?;
350
            let tip = cache.summary(r, &tip)?;
351
            Ok(pinned_sets
352
                .iter()
353
                .map(|p| cache.summary(r, p).ok().map(|s| tip.changes.iter().filter(|c| !s.changes.contains(*c)).count()))
354
                .collect::<Vec<_>>())
355
        })
356
        .await?;
357
    for (c, b) in out.iter_mut().zip(behind) {
358
        c.behind = b;
359
        c.colour = Colour::of(c.follow, b, c.bump, c.run.as_ref().map(|r| r.1.as_str()), unverified);
360
    }
361
    Ok(out)
362
}
363
364
/// What `consumer` follows, as its Follows panel shows: each upstream on
365
/// this hub it pins, with its status there.
366
pub async fn follows(app: &Shared, consumer: &RepoRow, account: Option<&Account>) -> Vec<(RepoRow, Consumer)> {
367
    let ups: Vec<i64> =
368
        sqlx::query_scalar("SELECT DISTINCT upstream_repo_id FROM diffusion_pins WHERE consumer_id = ? AND upstream_repo_id IS NOT NULL")
369
            .bind(consumer.id)
370
            .fetch_all(&app.db)
371
            .await
372
            .unwrap_or_default();
373
    let mut out = Vec::new();
374
    for id in ups {
375
        let Ok(Some(up)) = db::repos::get_by_id(&app.db, id).await else { continue };
376
        if !roles::allows(roles::role_for(&app.db, account, &up).await.ok().flatten(), crate::auth::Access::Read) {
377
            continue;
378
        }
379
        for c in consumers(app, &up, account).await.unwrap_or_default() {
380
            if c.owner == consumer.owner && c.name == consumer.name {
381
                out.push((up.clone(), c));
382
            }
383
        }
384
    }
385
    out
386
}
387
388
/// Every upstream on this hub with its consumers, for Admin › Diffusion.
389
pub async fn everything(app: &Shared, account: Option<&Account>) -> Vec<(RepoRow, Vec<Consumer>, bool)> {
390
    let ups: Vec<i64> = sqlx::query_scalar("SELECT DISTINCT upstream_repo_id FROM diffusion_pins WHERE upstream_repo_id IS NOT NULL")
391
        .fetch_all(&app.db)
392
        .await
393
        .unwrap_or_default();
394
    let mut out = Vec::new();
395
    for id in ups {
396
        let Ok(Some(up)) = db::repos::get_by_id(&app.db, id).await else { continue };
397
        let list = consumers(app, &up, account).await.unwrap_or_default();
398
        let unverified = unverified(app, &up).await;
399
        out.push((up, list, unverified));
400
    }
401
    out
402
}
403
404
/// The bookmark a consumer's bump for the subrepo at `path` lives on.
405
pub fn bump_bookmark(path: &str) -> String {
406
    format!("diffusion/{}", path.trim_matches('/'))
407
}
408
409
/// What a bump did.
410
#[derive(Clone, Debug, PartialEq, Eq)]
411
pub enum Bumped {
412
    /// The bump bookmark now holds the target plus one change moving the pin.
413
    Moved { bookmark: String, change: ChangeHash, heads: Vec<ChangeHash>, from: Vec<ChangeHash>, state: String },
414
    /// The pin already holds the upstream state.
415
    UpToDate,
416
    /// The bump bookmark already moves the pin to that state.
417
    Already { from: Vec<ChangeHash>, to: Vec<ChangeHash> },
418
    /// The pin names changes the upstream does not hold: not followed.
419
    Unknown,
420
    /// Taking the upstream's state with the pin's own extra changes would
421
    /// conflict.
422
    Conflicts,
423
    /// The consumer has no Oxygen pin of that upstream at `path` on its
424
    /// target bookmark.
425
    NoPin,
426
}
427
428
/// Where a consumer's pin `old` moves when the upstream reaches `new`,
429
/// worked out in the upstream (§4.3).
430
#[derive(Clone, Debug, PartialEq, Eq)]
431
pub enum Plan {
432
    /// To these heads, which add this many changes.
433
    To(Vec<ChangeHash>, usize),
434
    /// Nothing to add.
435
    UpToDate,
436
    /// The pin names changes the upstream does not hold (rewritten, or
437
    /// from elsewhere): not followed.
438
    Unknown,
439
    /// Taking `new` with the pin's own extra changes would conflict.
440
    Conflicts,
441
}
442
443
/// The pin `old` moved to the upstream's `new`. When the pin has changes
444
/// `new` lacks (say, from an upstream proposal not landed yet), they are
445
/// kept: changes that do not touch each other combine, so the move is to
446
/// both, never dropping what the consumer already relies on.
447
pub async fn plan(app: &Shared, upstream: &RepoName, old: Vec<ChangeHash>, new: Vec<ChangeHash>) -> Result<Plan, crate::repos::RepoError> {
448
    app.repos
449
        .read(upstream, move |r, cache| {
450
            let Ok(o) = cache.summary(r, &old) else { return Ok(Plan::Unknown) };
451
            let n = cache.summary(r, &new)?;
452
            if o.changes.iter().all(|c| n.changes.contains(c)) {
453
                let added = n.changes.len() - o.changes.len();
454
                return Ok(if added == 0 { Plan::UpToDate } else { Plan::To(new, added) });
455
            }
456
            let mut both = new.clone();
457
            both.extend(old.iter().copied());
458
            let heads = r.load_state(&both)?.heads();
459
            let b = cache.summary(r, &heads)?;
460
            if b.conflicted && !o.conflicted {
461
                return Ok(Plan::Conflicts);
462
            }
463
            let added = b.changes.len() - o.changes.len();
464
            Ok(if added == 0 { Plan::UpToDate } else { Plan::To(heads, added) })
465
        })
466
        .await
467
}
468
469
/// Move `consumer`'s pin of `upstream` at `path` to `new_heads`, on a bump
470
/// bookmark built from `target` (§4.3): one change, signed with the hub's
471
/// key, on the target's heads. The upstream decides forwardness.
472
pub async fn bump(
473
    app: &Shared,
474
    consumer: &RepoRow,
475
    target: &str,
476
    path: &str,
477
    upstream: &RepoRow,
478
    new_heads: Vec<ChangeHash>,
479
) -> Result<Bumped, crate::repos::RepoError> {
480
    use oxy_core::identity::Domain;
481
    use oxy_core::subrepo::Pin;
482
    let (Some(cname), Some(uname)) = (RepoName::new(&consumer.owner, &consumer.name), RepoName::new(&upstream.owner, &upstream.name))
483
    else {
484
        return Ok(Bumped::NoPin);
485
    };
486
    let upstream_id = app.repos.read(&uname, |r, _| Ok(r.id()?)).await?;
487
    // The consumer's current pin at `path` on its target, and on its bump
488
    // bookmark if it has one.
489
    let (t, p) = (target.to_string(), path.trim_matches('/').to_string());
490
    let (current, bumped) = app
491
        .repos
492
        .read(&cname, move |r, cache| {
493
            let pin_on = |bookmark: &str| -> Result<Option<Pin>, crate::repos::RepoError> {
494
                let heads = heads_of(r, bookmark)?;
495
                if heads.is_empty() {
496
                    return Ok(None);
497
                }
498
                let loaded = cache.load(r, &heads)?;
499
                let Some(f) = loaded.snapshot.files.get(&p) else { return Ok(None) };
500
                let oxy_core::state::FileContent::Opaque { blobs } = &f.content else { return Ok(None) };
501
                let Some(b) = blobs.first() else { return Ok(None) };
502
                Ok(Pin::decode(&r.read_blob(b)?).ok())
503
            };
504
            Ok((pin_on(&t)?, pin_on(&bump_bookmark(&p))?))
505
        })
506
        .await?;
507
    let Some(Pin::Oxy { repo, heads: old, bookmark }) = current else { return Ok(Bumped::NoPin) };
508
    if repo != upstream_id {
509
        return Ok(Bumped::NoPin);
510
    }
511
    let new_heads = match plan(app, &uname, old.clone(), new_heads.clone()).await? {
512
        Plan::To(heads, _) => heads,
513
        Plan::UpToDate => return Ok(Bumped::UpToDate),
514
        Plan::Unknown => return Ok(Bumped::Unknown),
515
        Plan::Conflicts => return Ok(Bumped::Conflicts),
516
    };
517
    if let Some(Pin::Oxy { heads: b, .. }) = &bumped {
518
        let (mut b, mut n) = (b.clone(), new_heads.clone());
519
        b.sort();
520
        n.sort();
521
        if b == n {
522
            return Ok(Bumped::Already { from: old, to: new_heads });
523
        }
524
    }
525
    let (key, secret) =
526
        crate::keys::load_secret(&app.config.keys_dir()).map_err(|e| crate::repos::RepoError::Io(std::io::Error::other(e.to_string())))?;
527
    let identity = app.hub_key.identity.clone();
528
    let upstream_label = format!("{}/{}", upstream.owner, upstream.name);
529
    let (t, p) = (target.to_string(), path.trim_matches('/').to_string());
530
    let pin = Pin::Oxy { repo, heads: new_heads.clone(), bookmark };
531
    let old = old.clone();
532
    let short: Vec<String> = new_heads.iter().map(|h| h.to_hex()[..12].to_string()).collect();
533
    let message = format!("Diffusion: move {p} to {upstream_label} {}", short.join("+"));
534
    app.repos
535
        .write(&cname, move |r, _| {
536
            let base = heads_of(r, &t)?;
537
            let change = r.build_pin_change(&base, &p, &pin, &message, key)?;
538
            let hash = change.hash();
539
            let sig = secret.sign(Domain::Change, &key, &hash);
540
            let mut state = r.load_state(&base)?;
541
            state.add(change.clone()).map_err(|e| crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(e.to_string())))?;
542
            let mut candidates = base.clone();
543
            candidates.push(hash);
544
            let heads = state.maximal(&candidates);
545
            let bookmark = bump_bookmark(&p);
546
            // The bump bookmark is the hub's own and is rebuilt on the
547
            // target each time, so the bump it replaces may go.
548
            let mut update = r.host_ref_update(&bookmark, &heads, Some((&key, &secret)))?;
549
            update.force = true;
550
            let state = update.new_state.to_hex();
551
            let report = r.apply_hosted(Some((change, vec![sig])), &[identity], update)?;
552
            if let Some(refused) = report.results.iter().find(|x| !x.ok) {
553
                return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!(
554
                    "the bump was refused: {}",
555
                    refused.reason
556
                ))));
557
            }
558
            Ok(Bumped::Moved { bookmark, change: hash, heads, from: old, state })
559
        })
560
        .await
561
}
562
563
/// The account Diffusion's proposals are opened as.
564
pub const ACCOUNT: &str = "diffusion";
565
566
/// The `diffusion` account, made on first use with no way to sign in.
567
pub async fn account(pool: &Pool) -> Option<Account> {
568
    if let Ok(Some(a)) = db::accounts::account_by_name(pool, ACCOUNT).await {
569
        return Some(a);
570
    }
571
    db::accounts::create_account(pool, ACCOUNT, "diffusion@localhost", "!", "", false).await.ok()
572
}
573
574
/// Whether `path` matches a `watch` pattern: `*` is any run of characters
575
/// within one path segment, `**` any run across segments, `?` one
576
/// character; a pattern without a wildcard also matches everything below
577
/// it, as a directory would.
578
pub fn watched(pattern: &str, path: &str) -> bool {
579
    fn m(p: &[u8], s: &[u8]) -> bool {
580
        match (p.first(), s.first()) {
581
            (None, None) => true,
582
            (Some(b'*'), _) if p.get(1) == Some(&b'*') => (0..=s.len()).any(|i| m(&p[2..], &s[i..])),
583
            (Some(b'*'), _) => (0..=s.len()).take_while(|&i| i == 0 || s[i - 1] != b'/').any(|i| m(&p[1..], &s[i..])),
584
            (Some(b'?'), Some(c)) if *c != b'/' => m(&p[1..], &s[1..]),
585
            (Some(a), Some(b)) if a == b => m(&p[1..], &s[1..]),
586
            _ => false,
587
        }
588
    }
589
    let p = pattern.trim().trim_matches('/');
590
    if p.is_empty() {
591
        return false;
592
    }
593
    m(p.as_bytes(), path.as_bytes()) || (!p.contains(['*', '?']) && path.starts_with(&format!("{p}/")))
594
}
595
596
/// What a bump brings: the upstream changes in `new` and not in `old`,
597
/// newest first, as Markdown lines linking to the upstream's change pages,
598
/// with those touching a `watch` pattern flagged (and listed again).
599
pub struct Changelog {
600
    pub lines: Vec<String>,
601
    pub watched: Vec<String>,
602
}
603
604
pub async fn changelog(app: &Shared, upstream: &RepoRow, old: Vec<ChangeHash>, new: Vec<ChangeHash>, watch: Vec<String>) -> Changelog {
605
    let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { return Changelog { lines: Vec::new(), watched: Vec::new() } };
606
    let linked: std::collections::HashMap<String, String> =
607
        db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
608
    let base = format!("/{}/{}", upstream.owner, upstream.name);
609
    app.repos
610
        .read(&name, move |r, cache| {
611
            let (o, n) = (cache.summary(r, &old)?, cache.summary(r, &new)?);
612
            let mut added: Vec<(u64, ChangeHash, String, String, Vec<String>)> = Vec::new();
613
            for h in n.changes.iter().filter(|c| !o.changes.contains(*c)) {
614
                let Ok(c) = r.store().get_change(h) else { continue };
615
                let key = c.author.to_hex();
616
                let who = linked.get(&key).cloned().unwrap_or_else(|| key[..12].to_string());
617
                let first = c.message.lines().next().unwrap_or("").trim().to_string();
618
                // The watched paths it touches, when the game watches any.
619
                let hits: Vec<String> = if watch.is_empty() {
620
                    Vec::new()
621
                } else {
622
                    crate::repos::view::change(r, cache, h)
623
                        .map(|d| d.files.into_iter().map(|f| f.path).filter(|p| watch.iter().any(|w| watched(w, p))).collect())
624
                        .unwrap_or_default()
625
                };
626
                added.push((c.hlc.wall_ms, *h, first, who, hits));
627
            }
628
            added.sort_by_key(|a| std::cmp::Reverse(a.0));
629
            let line = |h: &ChangeHash, msg: &str, who: &str, flag: bool| {
630
                format!(
631
                    "- {}[`{}`]({base}/change/{}) {} ({who})",
632
                    if flag { "⚑ " } else { "" },
633
                    &h.to_hex()[..12],
634
                    h.to_hex(),
635
                    msg.replace('\n', " ")
636
                )
637
            };
638
            let watched = added
639
                .iter()
640
                .filter(|a| !a.4.is_empty())
641
                .map(|(_, h, msg, who, hits)| {
642
                    format!(
643
                        "{} — touches {}",
644
                        line(h, msg, who, true),
645
                        hits.iter().map(|p| format!("`{p}`")).collect::<Vec<_>>().join(", ")
646
                    )
647
                })
648
                .collect();
649
            let lines = added.iter().map(|(_, h, msg, who, hits)| line(h, msg, who, !hits.is_empty())).collect();
650
            Ok(Changelog { lines, watched })
651
        })
652
        .await
653
        .unwrap_or(Changelog { lines: Vec::new(), watched: Vec::new() })
654
}
655
656
/// Why a bump was made, which its proposal says.
657
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
658
pub enum Why {
659
    /// The upstream's state passed its checks.
660
    Green,
661
    /// The upstream moved (the consumer follows every move).
662
    Moved,
663
    /// The upstream has no checks at all: nothing vouched for it, so the
664
    /// proposal is marked amber, `upstream unverified`.
665
    Unverified,
666
}
667
668
/// Open the bump proposal for `path`'s bump bookmark, or bring the open
669
/// one up to date: into `target`, by the `diffusion` account, labelled
670
/// `dependencies` (and `upstream unverified` while that is so), its body
671
/// the changelog from the pin `from` to `to`. Its number.
672
pub async fn propose(
673
    app: &Shared,
674
    consumer: &RepoRow,
675
    target: &str,
676
    path: &str,
677
    upstream: &RepoRow,
678
    (from, to): (Vec<ChangeHash>, Vec<ChangeHash>),
679
    (why, watch): (Why, Vec<String>),
680
) -> Option<i64> {
681
    use crate::db::proposals as pdb;
682
    let bookmark = bump_bookmark(path);
683
    let bookmark = bookmark.as_str();
684
    let me = account(&app.db).await?;
685
    let log = changelog(app, upstream, from, to.clone(), watch.clone()).await;
686
    let lines = log.lines;
687
    let flagged = if log.watched.is_empty() {
688
        String::new()
689
    } else {
690
        format!(
691
            "\n\n**Touches what you watch** ({}):\n\n{}",
692
            watch.iter().map(|w| format!("`{w}`")).collect::<Vec<_>>().join(", "),
693
            log.watched.join("\n")
694
        )
695
    };
696
    let slug = format!("{}/{}", upstream.owner, upstream.name);
697
    let short: Vec<String> = to.iter().map(|h| h.to_hex()[..12].to_string()).collect();
698
    let ub = &upstream.default_bookmark;
699
    let count = if lines.len() == 1 { "1 change".to_string() } else { format!("{} changes", lines.len()) };
700
    let title = format!("Diffusion: {path} to {slug} {ub} ({count})");
701
    let when = match why {
702
        Why::Green => "at its newest state whose checks passed",
703
        Why::Moved => "as it is now",
704
        Why::Unverified => "as it is now",
705
    };
706
    let amber = if why == Why::Unverified {
707
        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.")
708
    } else {
709
        String::new()
710
    };
711
    let body = format!(
712
        "Moves the subrepo `{path}` to [{slug}](/{slug})'s `{ub}`, {when} (`{}`). Only the pin changes; this repository's own checks test it.{amber}{flagged}\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.",
713
        short.join("+"),
714
        lines.join("\n")
715
    );
716
    let open = pdb::list(&app.db, consumer.id, &["open", "draft"]).await.ok()?.into_iter().find(|p| p.source_bookmark == bookmark);
717
    let (number, id) = match open {
718
        Some(p) => {
719
            if p.title != title || p.body != body {
720
                pdb::edit(&app.db, p.id, &title, &body, target).await.ok()?;
721
                pdb::add_event(&app.db, p.id, ACCOUNT, "updated", &short.join("+")).await.ok();
722
            }
723
            (p.number, p.id)
724
        }
725
        None => {
726
            let p = pdb::create(
727
                &app.db,
728
                pdb::NewProposal {
729
                    repo_id: consumer.id,
730
                    title: &title,
731
                    body: &body,
732
                    author_id: Some(me.id),
733
                    author: ACCOUNT,
734
                    draft: false,
735
                    target,
736
                    source_kind: "bookmark",
737
                    source_repo_id: None,
738
                    source_bookmark: bookmark,
739
                    source_changes: "",
740
                },
741
            )
742
            .await
743
            .ok()?;
744
            pdb::add_event(&app.db, p.id, ACCOUNT, "opened", "").await.ok();
745
            db::notify::index(&app.db, "proposal", consumer.id, p.id, p.number, &p.title, &p.body).await.ok();
746
            if let Ok(label) =
747
                db::issues::upsert_label(&app.db, consumer.id, "dependencies", "#0072ff", "A subrepo moves (Diffusion)").await
748
            {
749
                db::issues::set_proposal_label(&app.db, p.id, label.id, true).await.ok();
750
            }
751
            (p.number, p.id)
752
        }
753
    };
754
    // Amber while the upstream has no checks; cleared by a green bump.
755
    let unverified = db::issues::label_by_name(&app.db, consumer.id, "upstream unverified").await.ok().flatten();
756
    match (why == Why::Unverified, unverified) {
757
        (true, l) => {
758
            let l = match l {
759
                Some(l) => Some(l),
760
                None => db::issues::upsert_label(
761
                    &app.db,
762
                    consumer.id,
763
                    "upstream unverified",
764
                    "#e3a008",
765
                    "The upstream has no checks (Diffusion)",
766
                )
767
                .await
768
                .ok(),
769
            };
770
            if let Some(l) = l {
771
                db::issues::set_proposal_label(&app.db, id, l.id, true).await.ok();
772
            }
773
        }
774
        (false, Some(l)) => {
775
            db::issues::set_proposal_label(&app.db, id, l.id, false).await.ok();
776
        }
777
        (false, None) => {}
778
    }
779
    Some(number)
780
}
781
782
/// Start a bump's pipeline, as a push of it would. Boxed as `Send`, which
783
/// breaks the cycle between a bump starting runs and a passing run
784
/// starting bumps that the compiler cannot see through.
785
fn start_runs(
786
    app: Shared,
787
    row: RepoRow,
788
    bookmark: String,
789
    state: String,
790
    heads: Vec<ChangeHash>,
791
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
792
    Box::pin(async move { crate::flow::on_push(&app, &row, &bookmark, &state, &heads, ACCOUNT).await })
793
}
794
795
/// The text of `.oxymodules` on `bookmark` of `name`, if any.
796
async fn oxymodules(app: &Shared, name: &RepoName, bookmark: &str) -> Option<String> {
797
    let b = bookmark.to_string();
798
    app.repos
799
        .read(name, move |r, cache| {
800
            let heads = heads_of(r, &b)?;
801
            if heads.is_empty() {
802
                return Ok(None);
803
            }
804
            let loaded = cache.load(r, &heads)?;
805
            Ok(match loaded.snapshot.files.get(".oxymodules").map(|f| &f.content) {
806
                Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()),
807
                _ => None,
808
            })
809
        })
810
        .await
811
        .ok()
812
        .flatten()
813
}
814
815
/// The upstream `upstream` reached `heads` on its default bookmark: by a
816
/// push (`green` false) or a passing run of that state (`green` true).
817
/// Bump and propose in every consumer that follows it that way (§4.3).
818
pub async fn propagate(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool) {
819
    propagate_to(app, upstream, heads, green, None).await
820
}
821
822
/// `propagate`, to one consumer only when `only` names it.
823
async fn propagate_to(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool, only: Option<i64>) {
824
    let Some(uname) = RepoName::new(&upstream.owner, &upstream.name) else { return };
825
    let Ok(id) = app.repos.read(&uname, |r, _| Ok(r.id()?)).await else { return };
826
    let rows: Vec<(i64, String, String)> = sqlx::query_as("SELECT consumer_id, bookmark, path FROM diffusion_pins WHERE upstream = ?")
827
        .bind(hex::encode(id))
828
        .fetch_all(&app.db)
829
        .await
830
        .unwrap_or_default();
831
    let unverified = unverified(app, upstream).await;
832
    for (consumer_id, indexed, path) in rows {
833
        if only.is_some_and(|o| o != consumer_id) {
834
            continue;
835
        }
836
        let Ok(Some(consumer)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue };
837
        let Some(cname) = RepoName::new(&consumer.owner, &consumer.name) else { continue };
838
        let learned = target(&app.db, &consumer).await;
839
        let modules = oxymodules(app, &cname, &learned).await;
840
        let r = rule(&app.config.diffusion.follow, &consumer, modules.as_deref(), &path);
841
        let target = r.target.clone().unwrap_or(learned);
842
        if indexed != target {
843
            continue;
844
        }
845
        // An upstream with no checks never turns green: its moves count
846
        // for green followers too, marked amber (unverified).
847
        let go = match r.follow {
848
            Follow::Off => false,
849
            Follow::Green => green || unverified,
850
            Follow::Any => !green,
851
        };
852
        let why = if green {
853
            Why::Green
854
        } else if unverified {
855
            Why::Unverified
856
        } else {
857
            Why::Moved
858
        };
859
        if !go {
860
            continue;
861
        }
862
        match bump(app, &consumer, &target, &path, upstream, heads.clone()).await {
863
            Ok(Bumped::Moved { from, bookmark, heads: bumped, state, .. }) => {
864
                // Its pipeline runs as for a push, so the proposal is tested.
865
                tokio::spawn(start_runs(app.clone(), consumer.clone(), bookmark, state, bumped));
866
                let n = propose(app, &consumer, &target, &path, upstream, (from, heads.clone()), (why, r.watch.clone())).await;
867
                tracing::info!(
868
                    "diffusion: {}/{} {path} bumped to {}/{} (proposal {n:?})",
869
                    consumer.owner,
870
                    consumer.name,
871
                    upstream.owner,
872
                    upstream.name
873
                );
874
            }
875
            Ok(Bumped::Already { from, to }) => {
876
                // Already moved: its proposal's text and labels are brought
877
                // up to date all the same.
878
                propose(app, &consumer, &target, &path, upstream, (from, to), (why, r.watch.clone())).await;
879
            }
880
            Ok(other) => tracing::info!("diffusion: {}/{} {path}: no bump ({other:?})", consumer.owner, consumer.name),
881
            Err(e) => tracing::warn!("diffusion: bump {}/{} {path}: {e}", consumer.owner, consumer.name),
882
        }
883
    }
884
}
885
886
/// Whether `upstream` has no checks of its own: Flow is off for it, or
887
/// its default bookmark has never had a run. Its moves are then
888
/// "unverified" (amber), never green.
889
pub async fn unverified(app: &Shared, upstream: &RepoRow) -> bool {
890
    if !crate::flow::enabled(app, upstream) {
891
        return true;
892
    }
893
    let runs: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM flow_runs WHERE repo_id = ? AND bookmark = ?")
894
        .bind(upstream.id)
895
        .bind(&upstream.default_bookmark)
896
        .fetch_one(&app.db)
897
        .await
898
        .unwrap_or(0);
899
    runs == 0
900
}
901
902
/// The repository on this hub with Oxygen id `id` (hex).
903
async fn repo_by_oxy_id(app: &Shared, id: &str) -> Option<RepoRow> {
904
    for row in db::repos::list(&app.db).await.ok()? {
905
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
906
        if app.repos.read(&name, |r, _| Ok(r.id()?)).await.ok().map(hex::encode).as_deref() == Some(id) {
907
            return Some(row);
908
        }
909
    }
910
    None
911
}
912
913
/// The newest state of `upstream`'s default bookmark whose run passed.
914
async fn last_green(app: &Shared, upstream: &RepoRow) -> Option<Vec<ChangeHash>> {
915
    let heads: String =
916
        sqlx::query_scalar("SELECT heads FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND status = 'passed' ORDER BY id DESC LIMIT 1")
917
            .bind(upstream.id)
918
            .bind(&upstream.default_bookmark)
919
            .fetch_optional(&app.db)
920
            .await
921
            .ok()
922
            .flatten()?;
923
    let h: Vec<ChangeHash> = heads.split('+').filter_map(ChangeHash::from_hex).collect();
924
    (!h.is_empty()).then_some(h)
925
}
926
927
/// Bring `consumer` up to date with the upstreams it pins, at once: when
928
/// it turns Diffusion on, it is bumped to each upstream's newest state
929
/// that passed (or simply its newest, when it follows every move).
930
pub async fn catch_up(app: &Shared, consumer: &RepoRow) {
931
    let upstreams: Vec<String> = sqlx::query_scalar("SELECT DISTINCT upstream FROM diffusion_pins WHERE consumer_id = ?")
932
        .bind(consumer.id)
933
        .fetch_all(&app.db)
934
        .await
935
        .unwrap_or_default();
936
    for id in upstreams {
937
        let Some(upstream) = repo_by_oxy_id(app, &id).await else { continue };
938
        if let Some(h) = last_green(app, &upstream).await {
939
            propagate_to(app, &upstream, h, true, Some(consumer.id)).await;
940
        }
941
        let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { continue };
942
        let b = upstream.default_bookmark.clone();
943
        if let Ok(h) = app.repos.read(&name, move |r, _| heads_of(r, &b)).await {
944
            propagate_to(app, &upstream, h, false, Some(consumer.id)).await;
945
        }
946
    }
947
}
948
949
/// When a consumer takes an upstream's moves (§4.2).
950
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
951
#[serde(rename_all = "lowercase")]
952
pub enum Follow {
953
    Off,
954
    /// When the upstream state's checks pass.
955
    Green,
956
    /// On every move.
957
    Any,
958
}
959
960
impl Follow {
961
    pub fn parse(s: &str) -> Option<Follow> {
962
        match s.trim() {
963
            "off" => Some(Follow::Off),
964
            "green" => Some(Follow::Green),
965
            "any" => Some(Follow::Any),
966
            _ => None,
967
        }
968
    }
969
}
970
971
/// How one consumer follows one subrepo, from its `.oxymodules` entry, its
972
/// repository setting and the site's default, in that order.
973
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
974
pub struct Rule {
975
    pub follow: Follow,
976
    /// Land a green bump itself (D5); D1 only proposes.
977
    pub land_auto: bool,
978
    /// The bookmark to bump, when `.oxymodules` names one (else learned).
979
    pub target: Option<String>,
980
    /// Paths the consumer watches: upstream changes touching them are
981
    /// flagged in a bump's changelog.
982
    pub watch: Vec<String>,
983
    /// Where `follow` came from: `.oxymodules`, `setting` or `site`.
984
    pub from: &'static str,
985
}
986
987
/// The Diffusion keys of `path`'s entry in `.oxymodules` text: `follow`,
988
/// `land`, `target` and `watch` (comma-separated, or a TOML list).
989
pub fn module_keys(text: &str, path: &str) -> (Option<Follow>, Option<bool>, Option<String>, Vec<String>) {
990
    let (mut follow, mut land, mut target, mut watch) = (None, None, None, Vec::new());
991
    let mut here = false;
992
    for line in text.lines() {
993
        let line = line.trim();
994
        if line.is_empty() || line.starts_with('#') {
995
            continue;
996
        }
997
        if let Some(inner) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
998
            here = inner.trim().trim_matches('"').trim_end_matches('/') == path.trim_end_matches('/');
999
            continue;
1000
        }
1001
        let (true, Some((k, v))) = (here, line.split_once('=')) else { continue };
1002
        let v = v.trim();
1003
        let unquoted = v.trim_matches('"').trim();
1004
        match k.trim() {
1005
            "follow" => follow = Follow::parse(unquoted),
1006
            "land" => land = Some(unquoted == "auto"),
1007
            "target" if !unquoted.is_empty() => target = Some(unquoted.to_string()),
1008
            "watch" => {
1009
                watch = v
1010
                    .trim_start_matches('[')
1011
                    .trim_end_matches(']')
1012
                    .split(',')
1013
                    .map(|w| w.trim().trim_matches('"').trim().to_string())
1014
                    .filter(|w| !w.is_empty())
1015
                    .collect()
1016
            }
1017
            _ => {}
1018
        }
1019
    }
1020
    (follow, land, target, watch)
1021
}
1022
1023
/// How `row` follows its subrepo at `path`, given its `.oxymodules` text.
1024
pub fn rule(site_default: &str, row: &RepoRow, oxymodules: Option<&str>, path: &str) -> Rule {
1025
    let (follow, land, target, watch) = oxymodules.map(|t| module_keys(t, path)).unwrap_or_default();
1026
    let (follow, from) = match follow {
1027
        Some(f) => (f, ".oxymodules"),
1028
        None => match Follow::parse(&row.diffusion) {
1029
            Some(f) => (f, "setting"),
1030
            None => (Follow::parse(site_default).unwrap_or(Follow::Off), "site"),
1031
        },
1032
    };
1033
    Rule { follow, land_auto: land.unwrap_or(false), target, watch, from }
1034
}
1035
1036
#[cfg(test)]
1037
mod tests {
1038
    use super::*;
1039
1040
    const MODULES: &str = r#"
1041
[rstar-api]
1042
url = https://oxygenhub.io/doomsdayone/rstar-api
1043
follow = green
1044
land = "propose"
1045
target = develop
1046
watch = ["src/x16/irq*", "src/x16/frame*"]
1047
1048
[other]
1049
url = https://example/other
1050
follow = any
1051
"#;
1052
1053
    fn row(diffusion: &str) -> RepoRow {
1054
        RepoRow {
1055
            id: 1,
1056
            owner: "o".into(),
1057
            name: "n".into(),
1058
            description: String::new(),
1059
            default_bookmark: "main".into(),
1060
            visibility: "public".into(),
1061
            created_ms: 0,
1062
            updated_ms: 0,
1063
            git_mirror: false,
1064
            git_mirror_state: String::new(),
1065
            forked_from: None,
1066
            topics: String::new(),
1067
            flow: String::new(),
1068
            diffusion: diffusion.into(),
1069
            ..Default::default()
1070
        }
1071
    }
1072
1073
    #[test]
1074
    fn watch_patterns_match_paths() {
1075
        assert!(watched("src/x16/irq*", "src/x16/irq.s"));
1076
        assert!(watched("src/x16/irq*", "src/x16/irq_wait.c"));
1077
        assert!(!watched("src/x16/irq*", "src/x16/sub/irq.s"), "one segment");
1078
        assert!(watched("src/**/frame*.c", "src/x16/floor/frame_wait.c"));
1079
        assert!(watched("src/x16", "src/x16/bank.s"), "a directory");
1080
        assert!(!watched("src/x16", "src/x160/bank.s"));
1081
        assert!(watched("include/r?m.h", "include/rim.h"));
1082
        assert!(!watched("", "anything"));
1083
    }
1084
1085
    #[test]
1086
    fn oxymodules_keys_are_read_per_entry() {
1087
        let (f, land, target, watch) = module_keys(MODULES, "rstar-api");
1088
        assert_eq!((f, land, target.as_deref()), (Some(Follow::Green), Some(false), Some("develop")));
1089
        assert_eq!(watch, vec!["src/x16/irq*", "src/x16/frame*"]);
1090
        assert_eq!(module_keys(MODULES, "other").0, Some(Follow::Any));
1091
        assert_eq!(module_keys(MODULES, "missing"), (None, None, None, vec![]));
1092
        assert_eq!(module_keys("[a]\nwatch = x, y\n", "a").3, vec!["x", "y"]);
1093
    }
1094
1095
    #[test]
1096
    fn oxymodules_wins_then_the_setting_then_the_site() {
1097
        let r = rule("off", &row("any"), Some(MODULES), "rstar-api");
1098
        assert_eq!((r.follow, r.from), (Follow::Green, ".oxymodules"));
1099
        let r = rule("off", &row("any"), Some("[rstar-api]\nurl = x\n"), "rstar-api");
1100
        assert_eq!((r.follow, r.from), (Follow::Any, "setting"));
1101
        let r = rule("green", &row(""), None, "rstar-api");
1102
        assert_eq!((r.follow, r.from), (Follow::Green, "site"));
1103
        assert_eq!(rule("nonsense", &row(""), None, "x").follow, Follow::Off);
1104
    }
1105
}