use std::{
cmp::Ordering,
collections::{BTreeMap, HashMap, HashSet},
time::Duration,
};
use super::{
interest::{Cadence, Shown, SHOWN_POLL},
model::{BranchId, FetchPlan, Found, PrId, PrSummary, Rollup},
poller::WATCH_POLL,
service::{ShowRead, Snapshot, State},
state::Baseline,
watch,
};
pub(crate) const QUIET_REREAD: Duration = Duration::from_secs(10 * 60);
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct Due {
pub(super) plan: FetchPlan,
pub(super) wants_detail: HashSet<PrId>,
pub(super) shown_branches: HashSet<BranchId>,
}
#[derive(Default)]
struct Want {
cadence: Option<Cadence>,
linked: bool,
pending: bool,
unasked: bool,
}
impl Want {
fn at(&mut self, cadence: Cadence) {
self.cadence = Some(self.cadence.map_or(cadence, |fastest| fastest.min(cadence)));
}
}
pub(super) fn due(state: &State, now: u64) -> BTreeMap<String, Due> {
let mut prs: HashMap<&PrId, Want> = HashMap::new();
for (session, entry) in &state.sessions {
for link in entry.record.links() {
let leased = state
.interest
.cadence(session, &Shown::Linked(link.pr.clone()), now);
let watched = link
.watch
.as_ref()
.map(|watch| watch.baseline == Baseline::Pending);
let awaits_merge = link.awaits_merge();
if leased.is_none() && watched.is_none() && !awaits_merge {
continue;
}
let want = prs.entry(&link.pr).or_default();
want.linked = true;
if awaits_merge {
want.at(Cadence::Linked);
let asked_at = state.snapshots.get(&link.pr).and_then(|read| read.asked_at);
want.unasked |=
link.stood.is_none() && asked_at.is_some_and(|at| at / 1000 < link.linked_at);
}
if let Some(cadence) = leased {
want.at(cadence);
}
if let Some(pending) = watched {
want.at(Cadence::Watched);
want.pending |= pending;
}
}
}
let mut branches: HashMap<&BranchId, Cadence> = HashMap::new();
for (session, interest) in state.interest.sessions() {
let Some(branch) = interest.checkout().branch() else {
continue;
};
let Some(cadence) = state.interest.cadence(session, &Shown::Branch, now) else {
continue;
};
let default_now = state
.default_seen_at(branch)
.is_some_and(|at| Duration::from_millis(now.saturating_sub(at)) < QUIET_REREAD);
if default_now {
continue;
}
let fastest = branches.entry(branch).or_insert(cadence);
*fastest = (*fastest).min(cadence);
if let Some(pr) = state.found(branch) {
prs.entry(pr).or_default().at(cadence);
}
}
let mut hosts: BTreeMap<String, Due> = BTreeMap::new();
for (branch, cadence) in branches {
let asked_at = state.branches.get(branch).and_then(|read| read.asked_at);
if cadence.due(asked_at, now) {
let due = hosts.entry(branch.repo.host.clone()).or_default();
due.plan.branches.push(branch.clone());
match cadence {
Cadence::Shown => {
due.shown_branches.insert(branch.clone());
}
Cadence::Watched | Cadence::Listed | Cadence::Linked => {}
}
}
}
let mut linked: HashMap<&str, (Vec<&PrId>, bool)> = HashMap::new();
for (pr, want) in prs {
let Some(cadence) = want.cadence else {
continue;
};
let snapshot = state.snapshots.get(pr);
let is_due =
want.unasked || cadence.due(snapshot.and_then(|snapshot| snapshot.asked_at), now);
let host = pr.repo.host.as_str();
match cadence {
Cadence::Linked => {
let (prs, any_due) = linked.entry(host).or_default();
prs.push(pr);
*any_due |= is_due;
}
Cadence::Shown | Cadence::Watched | Cadence::Listed if !is_due => {}
Cadence::Shown | Cadence::Watched => {
let due = hosts.entry(host.to_owned()).or_default();
due.wants_detail.insert(pr.clone());
if want.pending || detail_due(snapshot, now) {
due.plan.details.push(pr.clone());
} else if want.linked {
due.plan.links.push(pr.clone());
}
}
Cadence::Listed => {
if want.linked {
let due = hosts.entry(host.to_owned()).or_default();
due.plan.links.push(pr.clone());
}
}
}
}
for (host, (prs, any_due)) in linked {
if any_due {
let due = hosts.entry(host.to_owned()).or_default();
due.plan.links.extend(prs.into_iter().cloned());
}
}
hosts.retain(|_, due| !due.plan.is_empty());
for due in hosts.values_mut() {
let FetchPlan {
branches,
links,
details,
} = &mut due.plan;
branches.sort_by(|a, b| {
(&a.repo.owner, &a.repo.name, &a.branch).cmp(&(&b.repo.owner, &b.repo.name, &b.branch))
});
links.sort_by(by_number);
details.sort_by(by_number);
}
hosts
}
pub(super) fn tick_period(state: &State, now: u64) -> Duration {
if state.interest.shows_any(now) {
SHOWN_POLL
} else {
WATCH_POLL
}
}
pub(super) fn shown(state: &State, now: u64) -> HashSet<PrId> {
let mut shown = HashSet::new();
for (_, interest) in state.interest.sessions() {
for target in interest.shown(now) {
match target {
Shown::Linked(pr) => {
shown.insert(pr.clone());
}
Shown::Branch => {
let found = interest
.checkout()
.branch()
.and_then(|branch| state.found(branch));
shown.extend(found.cloned());
}
}
}
}
shown
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ShowOf<'a> {
Linked(&'a PrId),
Branch(&'a BranchId),
}
enum Kept {
Answer,
Missing,
FailedAt(u64),
}
pub(super) fn show_reads(state: &State, of: ShowOf<'_>, read: ShowRead, now: u64) -> bool {
let kept = match of {
ShowOf::Linked(pr) => kept_detail(state.snapshots.get(pr)),
ShowOf::Branch(branch) => kept_lookup(state, branch),
};
match (read, kept) {
(ShowRead::Fresh, _) | (ShowRead::Cached, Kept::Missing) => true,
(ShowRead::Cached, Kept::Answer) => false,
(ShowRead::Cached, Kept::FailedAt(at)) => Cadence::Shown.due(Some(at), now),
}
}
fn kept_detail(snapshot: Option<&Snapshot>) -> Kept {
let Some(snapshot) = snapshot else {
return Kept::Missing;
};
let failed_at = snapshot.asked_at.max(snapshot.show_failed_at);
match (snapshot.answer(), &snapshot.trouble, failed_at) {
(Some(_), _, _) => Kept::Answer,
(None, Some(_), Some(at)) => Kept::FailedAt(at),
(None, Some(_), None) | (None, None, _) => Kept::Missing,
}
}
fn kept_lookup(state: &State, branch: &BranchId) -> Kept {
if state.is_default(branch) {
return Kept::Answer;
}
let Some(read) = state.branches.get(branch) else {
return Kept::Missing;
};
match (&read.found, &read.trouble, read.asked_at) {
(Some(Found::Pr(summary)), _, _) => kept_detail(state.snapshots.get(&summary.id)),
(Some(Found::None | Found::OnlyForks(_)), _, _) => Kept::Answer,
(None, Some(_), Some(at)) => Kept::FailedAt(at),
(None, Some(_), None) | (None, None, _) => Kept::Missing,
}
}
pub(super) fn detail_due(snapshot: Option<&Snapshot>, now: u64) -> bool {
let Some(snapshot) = snapshot else {
return true;
};
let Some(detailed) = &snapshot.detail else {
return true;
};
let detail = &detailed.detail;
let running = detail.unread_checks() > 0
|| detail
.checks
.iter()
.any(|check| watch::running(check.status))
|| snapshot
.summary
.as_ref()
.is_some_and(|summary| summary.change.rollup == Rollup::Pending);
running || Duration::from_millis(now.saturating_sub(detailed.at)) >= QUIET_REREAD
}
pub(super) fn moved_since_detail(snapshot: Option<&Snapshot>, summary: &PrSummary) -> bool {
snapshot
.and_then(|snapshot| snapshot.detail.as_ref())
.is_none_or(|detailed| !reads_as(&detailed.detail.summary, summary))
}
pub(super) fn reads_as(last: &PrSummary, summary: &PrSummary) -> bool {
last.change == summary.change && last.state == summary.state
}
pub(super) fn by_number(a: &PrId, b: &PrId) -> Ordering {
(&a.repo.owner, &a.repo.name, a.number).cmp(&(&b.repo.owner, &b.repo.name, b.number))
}
#[cfg(test)]
#[path = "due_tests.rs"]
mod tests;