| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 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 |
|
| 18 |
pub const LEARN_DAYS: i64 = 90; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 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 |
|
| 39 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 91 |
|
| 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 |
|
| 107 |
|
| 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 |
|
| 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 |
|
| 120 |
pub pinned: Vec<String>, |
| 121 |
|
| 122 |
|
| 123 |
pub behind: Option<usize>, |
| 124 |
} |
| 125 |
|
| 126 |
|
| 127 |
|
| 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 |
|
| 171 |
pub fn bump_bookmark(path: &str) -> String { |
| 172 |
format!("diffusion/{}", path.trim_matches('/')) |
| 173 |
} |
| 174 |
|
| 175 |
|
| 176 |
#[derive(Clone, Debug, PartialEq, Eq)] |
| 177 |
pub enum Bumped { |
| 178 |
|
| 179 |
Moved { bookmark: String, change: ChangeHash, heads: Vec<ChangeHash>, from: Vec<ChangeHash>, state: String }, |
| 180 |
|
| 181 |
UpToDate, |
| 182 |
|
| 183 |
Already, |
| 184 |
|
| 185 |
|
| 186 |
Backwards, |
| 187 |
|
| 188 |
|
| 189 |
NoPin, |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
pub async fn ahead_of( |
| 196 |
app: &Shared, |
| 197 |
upstream: &RepoName, |
| 198 |
old: Vec<ChangeHash>, |
| 199 |
new: Vec<ChangeHash>, |
| 200 |
) -> Result<Option<usize>, crate::repos::RepoError> { |
| 201 |
app.repos |
| 202 |
.read(upstream, move |r, cache| { |
| 203 |
let (o, n) = (cache.summary(r, &old)?, cache.summary(r, &new)?); |
| 204 |
if !o.changes.iter().all(|c| n.changes.contains(c)) { |
| 205 |
return Ok(None); |
| 206 |
} |
| 207 |
Ok(Some(n.changes.len() - o.changes.len())) |
| 208 |
}) |
| 209 |
.await |
| 210 |
} |
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
pub async fn bump( |
| 216 |
app: &Shared, |
| 217 |
consumer: &RepoRow, |
| 218 |
target: &str, |
| 219 |
path: &str, |
| 220 |
upstream: &RepoRow, |
| 221 |
new_heads: Vec<ChangeHash>, |
| 222 |
) -> Result<Bumped, crate::repos::RepoError> { |
| 223 |
use oxy_core::identity::Domain; |
| 224 |
use oxy_core::subrepo::Pin; |
| 225 |
let (Some(cname), Some(uname)) = (RepoName::new(&consumer.owner, &consumer.name), RepoName::new(&upstream.owner, &upstream.name)) |
| 226 |
else { |
| 227 |
return Ok(Bumped::NoPin); |
| 228 |
}; |
| 229 |
let upstream_id = app.repos.read(&uname, |r, _| Ok(r.id()?)).await?; |
| 230 |
|
| 231 |
|
| 232 |
let (t, p) = (target.to_string(), path.trim_matches('/').to_string()); |
| 233 |
let (current, bumped) = app |
| 234 |
.repos |
| 235 |
.read(&cname, move |r, cache| { |
| 236 |
let pin_on = |bookmark: &str| -> Result<Option<Pin>, crate::repos::RepoError> { |
| 237 |
let heads = heads_of(r, bookmark)?; |
| 238 |
if heads.is_empty() { |
| 239 |
return Ok(None); |
| 240 |
} |
| 241 |
let loaded = cache.load(r, &heads)?; |
| 242 |
let Some(f) = loaded.snapshot.files.get(&p) else { return Ok(None) }; |
| 243 |
let oxy_core::state::FileContent::Opaque { blobs } = &f.content else { return Ok(None) }; |
| 244 |
let Some(b) = blobs.first() else { return Ok(None) }; |
| 245 |
Ok(Pin::decode(&r.read_blob(b)?).ok()) |
| 246 |
}; |
| 247 |
Ok((pin_on(&t)?, pin_on(&bump_bookmark(&p))?)) |
| 248 |
}) |
| 249 |
.await?; |
| 250 |
let Some(Pin::Oxy { repo, heads: old, bookmark }) = current else { return Ok(Bumped::NoPin) }; |
| 251 |
if let Some(Pin::Oxy { heads: b, .. }) = &bumped { |
| 252 |
let (mut b, mut n) = (b.clone(), new_heads.clone()); |
| 253 |
b.sort(); |
| 254 |
n.sort(); |
| 255 |
if b == n { |
| 256 |
return Ok(Bumped::Already); |
| 257 |
} |
| 258 |
} |
| 259 |
if repo != upstream_id { |
| 260 |
return Ok(Bumped::NoPin); |
| 261 |
} |
| 262 |
match ahead_of(app, &uname, old.clone(), new_heads.clone()).await? { |
| 263 |
None => return Ok(Bumped::Backwards), |
| 264 |
Some(0) => return Ok(Bumped::UpToDate), |
| 265 |
Some(_) => {} |
| 266 |
} |
| 267 |
let (key, secret) = |
| 268 |
crate::keys::load_secret(&app.config.keys_dir()).map_err(|e| crate::repos::RepoError::Io(std::io::Error::other(e.to_string())))?; |
| 269 |
let identity = app.hub_key.identity.clone(); |
| 270 |
let upstream_label = format!("{}/{}", upstream.owner, upstream.name); |
| 271 |
let (t, p) = (target.to_string(), path.trim_matches('/').to_string()); |
| 272 |
let pin = Pin::Oxy { repo, heads: new_heads.clone(), bookmark }; |
| 273 |
let old = old.clone(); |
| 274 |
let short: Vec<String> = new_heads.iter().map(|h| h.to_hex()[..12].to_string()).collect(); |
| 275 |
let message = format!("Diffusion: move {p} to {upstream_label} {}", short.join("+")); |
| 276 |
app.repos |
| 277 |
.write(&cname, move |r, _| { |
| 278 |
let base = heads_of(r, &t)?; |
| 279 |
let change = r.build_pin_change(&base, &p, &pin, &message, key)?; |
| 280 |
let hash = change.hash(); |
| 281 |
let sig = secret.sign(Domain::Change, &key, &hash); |
| 282 |
let mut state = r.load_state(&base)?; |
| 283 |
state.add(change.clone()).map_err(|e| crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(e.to_string())))?; |
| 284 |
let mut candidates = base.clone(); |
| 285 |
candidates.push(hash); |
| 286 |
let heads = state.maximal(&candidates); |
| 287 |
let bookmark = bump_bookmark(&p); |
| 288 |
|
| 289 |
|
| 290 |
let mut update = r.host_ref_update(&bookmark, &heads, Some((&key, &secret)))?; |
| 291 |
update.force = true; |
| 292 |
let state = update.new_state.to_hex(); |
| 293 |
let report = r.apply_hosted(Some((change, vec![sig])), &[identity], update)?; |
| 294 |
if let Some(refused) = report.results.iter().find(|x| !x.ok) { |
| 295 |
return Err(crate::repos::RepoError::Oxy(oxy_core::repo::RepoError::Msg(format!( |
| 296 |
"the bump was refused: {}", |
| 297 |
refused.reason |
| 298 |
)))); |
| 299 |
} |
| 300 |
Ok(Bumped::Moved { bookmark, change: hash, heads, from: old, state }) |
| 301 |
}) |
| 302 |
.await |
| 303 |
} |
| 304 |
|
| 305 |
|
| 306 |
pub const ACCOUNT: &str = "diffusion"; |
| 307 |
|
| 308 |
|
| 309 |
pub async fn account(pool: &Pool) -> Option<Account> { |
| 310 |
if let Ok(Some(a)) = db::accounts::account_by_name(pool, ACCOUNT).await { |
| 311 |
return Some(a); |
| 312 |
} |
| 313 |
db::accounts::create_account(pool, ACCOUNT, "diffusion@localhost", "!", "", false).await.ok() |
| 314 |
} |
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
pub async fn changelog(app: &Shared, upstream: &RepoRow, old: Vec<ChangeHash>, new: Vec<ChangeHash>) -> Vec<String> { |
| 319 |
let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { return Vec::new() }; |
| 320 |
let linked: std::collections::HashMap<String, String> = |
| 321 |
db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect(); |
| 322 |
let base = format!("/{}/{}", upstream.owner, upstream.name); |
| 323 |
app.repos |
| 324 |
.read(&name, move |r, cache| { |
| 325 |
let (o, n) = (cache.summary(r, &old)?, cache.summary(r, &new)?); |
| 326 |
let mut added: Vec<(u64, ChangeHash, String, String)> = Vec::new(); |
| 327 |
for h in n.changes.iter().filter(|c| !o.changes.contains(*c)) { |
| 328 |
let Ok(c) = r.store().get_change(h) else { continue }; |
| 329 |
let key = c.author.to_hex(); |
| 330 |
let who = linked.get(&key).cloned().unwrap_or_else(|| key[..12].to_string()); |
| 331 |
let first = c.message.lines().next().unwrap_or("").trim().to_string(); |
| 332 |
added.push((c.hlc.wall_ms, *h, first, who)); |
| 333 |
} |
| 334 |
added.sort_by_key(|a| std::cmp::Reverse(a.0)); |
| 335 |
Ok(added |
| 336 |
.into_iter() |
| 337 |
.map(|(_, h, msg, who)| { |
| 338 |
format!("- [`{}`]({base}/change/{}) {} ({who})", &h.to_hex()[..12], h.to_hex(), msg.replace('\n', " ")) |
| 339 |
}) |
| 340 |
.collect()) |
| 341 |
}) |
| 342 |
.await |
| 343 |
.unwrap_or_default() |
| 344 |
} |
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
pub async fn propose( |
| 350 |
app: &Shared, |
| 351 |
consumer: &RepoRow, |
| 352 |
target: &str, |
| 353 |
path: &str, |
| 354 |
upstream: &RepoRow, |
| 355 |
from: Vec<ChangeHash>, |
| 356 |
to: Vec<ChangeHash>, |
| 357 |
) -> Option<i64> { |
| 358 |
use crate::db::proposals as pdb; |
| 359 |
let bookmark = bump_bookmark(path); |
| 360 |
let bookmark = bookmark.as_str(); |
| 361 |
let me = account(&app.db).await?; |
| 362 |
let lines = changelog(app, upstream, from, to.clone()).await; |
| 363 |
let slug = format!("{}/{}", upstream.owner, upstream.name); |
| 364 |
let short: Vec<String> = to.iter().map(|h| h.to_hex()[..12].to_string()).collect(); |
| 365 |
let title = format!( |
| 366 |
"Diffusion: {path} to {slug} {} ({})", |
| 367 |
short.join("+"), |
| 368 |
if lines.len() == 1 { "1 change".into() } else { format!("{} changes", lines.len()) } |
| 369 |
); |
| 370 |
let body = format!( |
| 371 |
"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.", |
| 372 |
if Follow::parse(&consumer.diffusion) == Some(Follow::Any) { "moved" } else { "passed its checks" }, |
| 373 |
lines.len(), |
| 374 |
if lines.len() == 1 { "" } else { "s" }, |
| 375 |
lines.join("\n") |
| 376 |
); |
| 377 |
let open = pdb::list(&app.db, consumer.id, &["open", "draft"]).await.ok()?.into_iter().find(|p| p.source_bookmark == bookmark); |
| 378 |
let number = match open { |
| 379 |
Some(p) => { |
| 380 |
pdb::edit(&app.db, p.id, &title, &body, target).await.ok()?; |
| 381 |
pdb::add_event(&app.db, p.id, ACCOUNT, "updated", &short.join("+")).await.ok(); |
| 382 |
p.number |
| 383 |
} |
| 384 |
None => { |
| 385 |
let p = pdb::create( |
| 386 |
&app.db, |
| 387 |
pdb::NewProposal { |
| 388 |
repo_id: consumer.id, |
| 389 |
title: &title, |
| 390 |
body: &body, |
| 391 |
author_id: Some(me.id), |
| 392 |
author: ACCOUNT, |
| 393 |
draft: false, |
| 394 |
target, |
| 395 |
source_kind: "bookmark", |
| 396 |
source_repo_id: None, |
| 397 |
source_bookmark: bookmark, |
| 398 |
source_changes: "", |
| 399 |
}, |
| 400 |
) |
| 401 |
.await |
| 402 |
.ok()?; |
| 403 |
pdb::add_event(&app.db, p.id, ACCOUNT, "opened", "").await.ok(); |
| 404 |
db::notify::index(&app.db, "proposal", consumer.id, p.id, p.number, &p.title, &p.body).await.ok(); |
| 405 |
if let Ok(label) = |
| 406 |
db::issues::upsert_label(&app.db, consumer.id, "dependencies", "#0072ff", "A subrepo moves (Diffusion)").await |
| 407 |
{ |
| 408 |
db::issues::set_proposal_label(&app.db, p.id, label.id, true).await.ok(); |
| 409 |
} |
| 410 |
p.number |
| 411 |
} |
| 412 |
}; |
| 413 |
Some(number) |
| 414 |
} |
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
fn start_runs( |
| 420 |
app: Shared, |
| 421 |
row: RepoRow, |
| 422 |
bookmark: String, |
| 423 |
state: String, |
| 424 |
heads: Vec<ChangeHash>, |
| 425 |
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> { |
| 426 |
Box::pin(async move { crate::flow::on_push(&app, &row, &bookmark, &state, &heads, ACCOUNT).await }) |
| 427 |
} |
| 428 |
|
| 429 |
|
| 430 |
async fn oxymodules(app: &Shared, name: &RepoName, bookmark: &str) -> Option<String> { |
| 431 |
let b = bookmark.to_string(); |
| 432 |
app.repos |
| 433 |
.read(name, move |r, cache| { |
| 434 |
let heads = heads_of(r, &b)?; |
| 435 |
if heads.is_empty() { |
| 436 |
return Ok(None); |
| 437 |
} |
| 438 |
let loaded = cache.load(r, &heads)?; |
| 439 |
Ok(match loaded.snapshot.files.get(".oxymodules").map(|f| &f.content) { |
| 440 |
Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()), |
| 441 |
_ => None, |
| 442 |
}) |
| 443 |
}) |
| 444 |
.await |
| 445 |
.ok() |
| 446 |
.flatten() |
| 447 |
} |
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
pub async fn propagate(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool) { |
| 453 |
propagate_to(app, upstream, heads, green, None).await |
| 454 |
} |
| 455 |
|
| 456 |
|
| 457 |
async fn propagate_to(app: &Shared, upstream: &RepoRow, heads: Vec<ChangeHash>, green: bool, only: Option<i64>) { |
| 458 |
let Some(uname) = RepoName::new(&upstream.owner, &upstream.name) else { return }; |
| 459 |
let Ok(id) = app.repos.read(&uname, |r, _| Ok(r.id()?)).await else { return }; |
| 460 |
let rows: Vec<(i64, String, String)> = sqlx::query_as("SELECT consumer_id, bookmark, path FROM diffusion_pins WHERE upstream = ?") |
| 461 |
.bind(hex::encode(id)) |
| 462 |
.fetch_all(&app.db) |
| 463 |
.await |
| 464 |
.unwrap_or_default(); |
| 465 |
for (consumer_id, indexed, path) in rows { |
| 466 |
if only.is_some_and(|o| o != consumer_id) { |
| 467 |
continue; |
| 468 |
} |
| 469 |
let Ok(Some(consumer)) = db::repos::get_by_id(&app.db, consumer_id).await else { continue }; |
| 470 |
let Some(cname) = RepoName::new(&consumer.owner, &consumer.name) else { continue }; |
| 471 |
let learned = target(&app.db, &consumer).await; |
| 472 |
let modules = oxymodules(app, &cname, &learned).await; |
| 473 |
let r = rule(&app.config.diffusion.follow, &consumer, modules.as_deref(), &path); |
| 474 |
let target = r.target.clone().unwrap_or(learned); |
| 475 |
if indexed != target { |
| 476 |
continue; |
| 477 |
} |
| 478 |
let go = match r.follow { |
| 479 |
Follow::Off => false, |
| 480 |
Follow::Green => green, |
| 481 |
Follow::Any => !green, |
| 482 |
}; |
| 483 |
if !go { |
| 484 |
continue; |
| 485 |
} |
| 486 |
match bump(app, &consumer, &target, &path, upstream, heads.clone()).await { |
| 487 |
Ok(Bumped::Moved { from, bookmark, heads: bumped, state, .. }) => { |
| 488 |
|
| 489 |
tokio::spawn(start_runs(app.clone(), consumer.clone(), bookmark, state, bumped)); |
| 490 |
let n = propose(app, &consumer, &target, &path, upstream, from, heads.clone()).await; |
| 491 |
tracing::info!( |
| 492 |
"diffusion: {}/{} {path} bumped to {}/{} (proposal {n:?})", |
| 493 |
consumer.owner, |
| 494 |
consumer.name, |
| 495 |
upstream.owner, |
| 496 |
upstream.name |
| 497 |
); |
| 498 |
} |
| 499 |
Ok(_) => {} |
| 500 |
Err(e) => tracing::warn!("diffusion: bump {}/{} {path}: {e}", consumer.owner, consumer.name), |
| 501 |
} |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
|
| 506 |
async fn repo_by_oxy_id(app: &Shared, id: &str) -> Option<RepoRow> { |
| 507 |
for row in db::repos::list(&app.db).await.ok()? { |
| 508 |
let Some(name) = RepoName::new(&row.owner, &row.name) else { continue }; |
| 509 |
if app.repos.read(&name, |r, _| Ok(r.id()?)).await.ok().map(hex::encode).as_deref() == Some(id) { |
| 510 |
return Some(row); |
| 511 |
} |
| 512 |
} |
| 513 |
None |
| 514 |
} |
| 515 |
|
| 516 |
|
| 517 |
async fn last_green(app: &Shared, upstream: &RepoRow) -> Option<Vec<ChangeHash>> { |
| 518 |
let heads: String = |
| 519 |
sqlx::query_scalar("SELECT heads FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND status = 'passed' ORDER BY id DESC LIMIT 1") |
| 520 |
.bind(upstream.id) |
| 521 |
.bind(&upstream.default_bookmark) |
| 522 |
.fetch_optional(&app.db) |
| 523 |
.await |
| 524 |
.ok() |
| 525 |
.flatten()?; |
| 526 |
let h: Vec<ChangeHash> = heads.split('+').filter_map(ChangeHash::from_hex).collect(); |
| 527 |
(!h.is_empty()).then_some(h) |
| 528 |
} |
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
pub async fn catch_up(app: &Shared, consumer: &RepoRow) { |
| 534 |
let upstreams: Vec<String> = sqlx::query_scalar("SELECT DISTINCT upstream FROM diffusion_pins WHERE consumer_id = ?") |
| 535 |
.bind(consumer.id) |
| 536 |
.fetch_all(&app.db) |
| 537 |
.await |
| 538 |
.unwrap_or_default(); |
| 539 |
for id in upstreams { |
| 540 |
let Some(upstream) = repo_by_oxy_id(app, &id).await else { continue }; |
| 541 |
if let Some(h) = last_green(app, &upstream).await { |
| 542 |
propagate_to(app, &upstream, h, true, Some(consumer.id)).await; |
| 543 |
} |
| 544 |
let Some(name) = RepoName::new(&upstream.owner, &upstream.name) else { continue }; |
| 545 |
let b = upstream.default_bookmark.clone(); |
| 546 |
if let Ok(h) = app.repos.read(&name, move |r, _| heads_of(r, &b)).await { |
| 547 |
propagate_to(app, &upstream, h, false, Some(consumer.id)).await; |
| 548 |
} |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
|
| 553 |
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] |
| 554 |
#[serde(rename_all = "lowercase")] |
| 555 |
pub enum Follow { |
| 556 |
Off, |
| 557 |
|
| 558 |
Green, |
| 559 |
|
| 560 |
Any, |
| 561 |
} |
| 562 |
|
| 563 |
impl Follow { |
| 564 |
pub fn parse(s: &str) -> Option<Follow> { |
| 565 |
match s.trim() { |
| 566 |
"off" => Some(Follow::Off), |
| 567 |
"green" => Some(Follow::Green), |
| 568 |
"any" => Some(Follow::Any), |
| 569 |
_ => None, |
| 570 |
} |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
|
| 575 |
|
| 576 |
#[derive(Clone, Debug, PartialEq, Eq, Serialize)] |
| 577 |
pub struct Rule { |
| 578 |
pub follow: Follow, |
| 579 |
|
| 580 |
pub land_auto: bool, |
| 581 |
|
| 582 |
pub target: Option<String>, |
| 583 |
|
| 584 |
|
| 585 |
pub watch: Vec<String>, |
| 586 |
|
| 587 |
pub from: &'static str, |
| 588 |
} |
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
pub fn module_keys(text: &str, path: &str) -> (Option<Follow>, Option<bool>, Option<String>, Vec<String>) { |
| 593 |
let (mut follow, mut land, mut target, mut watch) = (None, None, None, Vec::new()); |
| 594 |
let mut here = false; |
| 595 |
for line in text.lines() { |
| 596 |
let line = line.trim(); |
| 597 |
if line.is_empty() || line.starts_with('#') { |
| 598 |
continue; |
| 599 |
} |
| 600 |
if let Some(inner) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { |
| 601 |
here = inner.trim().trim_matches('"').trim_end_matches('/') == path.trim_end_matches('/'); |
| 602 |
continue; |
| 603 |
} |
| 604 |
let (true, Some((k, v))) = (here, line.split_once('=')) else { continue }; |
| 605 |
let v = v.trim(); |
| 606 |
let unquoted = v.trim_matches('"').trim(); |
| 607 |
match k.trim() { |
| 608 |
"follow" => follow = Follow::parse(unquoted), |
| 609 |
"land" => land = Some(unquoted == "auto"), |
| 610 |
"target" if !unquoted.is_empty() => target = Some(unquoted.to_string()), |
| 611 |
"watch" => { |
| 612 |
watch = v |
| 613 |
.trim_start_matches('[') |
| 614 |
.trim_end_matches(']') |
| 615 |
.split(',') |
| 616 |
.map(|w| w.trim().trim_matches('"').trim().to_string()) |
| 617 |
.filter(|w| !w.is_empty()) |
| 618 |
.collect() |
| 619 |
} |
| 620 |
_ => {} |
| 621 |
} |
| 622 |
} |
| 623 |
(follow, land, target, watch) |
| 624 |
} |
| 625 |
|
| 626 |
|
| 627 |
pub fn rule(site_default: &str, row: &RepoRow, oxymodules: Option<&str>, path: &str) -> Rule { |
| 628 |
let (follow, land, target, watch) = oxymodules.map(|t| module_keys(t, path)).unwrap_or_default(); |
| 629 |
let (follow, from) = match follow { |
| 630 |
Some(f) => (f, ".oxymodules"), |
| 631 |
None => match Follow::parse(&row.diffusion) { |
| 632 |
Some(f) => (f, "setting"), |
| 633 |
None => (Follow::parse(site_default).unwrap_or(Follow::Off), "site"), |
| 634 |
}, |
| 635 |
}; |
| 636 |
Rule { follow, land_auto: land.unwrap_or(false), target, watch, from } |
| 637 |
} |
| 638 |
|
| 639 |
#[cfg(test)] |
| 640 |
mod tests { |
| 641 |
use super::*; |
| 642 |
|
| 643 |
const MODULES: &str = r#" |
| 644 |
[rstar-api] |
| 645 |
url = https://oxygenhub.io/doomsdayone/rstar-api |
| 646 |
follow = green |
| 647 |
land = "propose" |
| 648 |
target = develop |
| 649 |
watch = ["src/x16/irq*", "src/x16/frame*"] |
| 650 |
|
| 651 |
[other] |
| 652 |
url = https://example/other |
| 653 |
follow = any |
| 654 |
"#; |
| 655 |
|
| 656 |
fn row(diffusion: &str) -> RepoRow { |
| 657 |
RepoRow { |
| 658 |
id: 1, |
| 659 |
owner: "o".into(), |
| 660 |
name: "n".into(), |
| 661 |
description: String::new(), |
| 662 |
default_bookmark: "main".into(), |
| 663 |
visibility: "public".into(), |
| 664 |
created_ms: 0, |
| 665 |
updated_ms: 0, |
| 666 |
git_mirror: false, |
| 667 |
git_mirror_state: String::new(), |
| 668 |
forked_from: None, |
| 669 |
topics: String::new(), |
| 670 |
flow: String::new(), |
| 671 |
diffusion: diffusion.into(), |
| 672 |
..Default::default() |
| 673 |
} |
| 674 |
} |
| 675 |
|
| 676 |
#[test] |
| 677 |
fn oxymodules_keys_are_read_per_entry() { |
| 678 |
let (f, land, target, watch) = module_keys(MODULES, "rstar-api"); |
| 679 |
assert_eq!((f, land, target.as_deref()), (Some(Follow::Green), Some(false), Some("develop"))); |
| 680 |
assert_eq!(watch, vec!["src/x16/irq*", "src/x16/frame*"]); |
| 681 |
assert_eq!(module_keys(MODULES, "other").0, Some(Follow::Any)); |
| 682 |
assert_eq!(module_keys(MODULES, "missing"), (None, None, None, vec![])); |
| 683 |
assert_eq!(module_keys("[a]\nwatch = x, y\n", "a").3, vec!["x", "y"]); |
| 684 |
} |
| 685 |
|
| 686 |
#[test] |
| 687 |
fn oxymodules_wins_then_the_setting_then_the_site() { |
| 688 |
let r = rule("off", &row("any"), Some(MODULES), "rstar-api"); |
| 689 |
assert_eq!((r.follow, r.from), (Follow::Green, ".oxymodules")); |
| 690 |
let r = rule("off", &row("any"), Some("[rstar-api]\nurl = x\n"), "rstar-api"); |
| 691 |
assert_eq!((r.follow, r.from), (Follow::Any, "setting")); |
| 692 |
let r = rule("green", &row(""), None, "rstar-api"); |
| 693 |
assert_eq!((r.follow, r.from), (Follow::Green, "site")); |
| 694 |
assert_eq!(rule("nonsense", &row(""), None, "x").follow, Follow::Off); |
| 695 |
} |
| 696 |
} |