use std::{
collections::{HashMap, HashSet},
sync::{Arc, Mutex, PoisonError},
time::Duration,
};
use rho_sdk::SessionId;
use tokio::sync::Notify;
use super::{
due::{self, Due},
gh::{Forge, ReadError},
model::{Batch, BranchId, Budget, FetchPlan, Found, PrDetail, PrId},
reads::{keep, read_into, Read, Reads},
record::{SessionRecord, NEWS_PER_SESSION},
service::{Detailed, Shared, State, Trouble},
state::{CheckTally, News},
watch::{self, Report},
};
pub(crate) const WATCH_POLL: Duration = Duration::from_secs(60);
pub(crate) const BUDGET_FLOOR: u32 = 50;
pub(crate) const WATCHES_PER_SESSION: usize = 25;
const DEAREST_MEASURED_COST: u32 = 10;
#[derive(Debug, Default)]
pub(super) struct Budgets(Mutex<HashMap<String, Budget>>);
impl Budgets {
pub(super) fn paused(&self, host: &str, now: u64) -> Option<Budget> {
let budgets = self.0.lock().unwrap_or_else(PoisonError::into_inner);
let budget = budgets.get(host)?;
let now = i64::try_from(now / 1000).unwrap_or(i64::MAX);
(budget.remaining <= BUDGET_FLOOR && now < budget.resets_at).then(|| budget.clone())
}
fn keep(&self, host: &str, budget: Budget) {
self.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(host.to_owned(), budget);
}
}
pub(super) struct Reader {
forge: Arc<dyn Forge>,
budgets: Arc<Budgets>,
}
impl Reader {
pub(super) fn new(forge: Arc<dyn Forge>, budgets: Arc<Budgets>) -> Self {
Self { forge, budgets }
}
pub(super) fn paused(&self, host: &str, now: u64) -> Option<Budget> {
self.budgets.paused(host, now)
}
pub(super) async fn read(&mut self, host: &str, plan: &FetchPlan) -> Result<Batch, ReadError> {
let read = self.forge.read(host, plan).await;
if let Ok(Batch {
budget: Some(budget),
..
}) = &read
{
self.keep_budget(host, budget);
}
read
}
fn keep_budget(&mut self, host: &str, budget: &Budget) {
let Budget {
remaining,
resets_at,
cost,
} = *budget;
match cost {
Some(cost) if cost > DEAREST_MEASURED_COST => tracing::warn!(
host,
cost,
remaining,
dearest_measured = DEAREST_MEASURED_COST,
"a pull request query cost more rate-limit points than rho measured for its dearest"
),
cost => tracing::debug!(host, ?cost, remaining, "read pull requests"),
}
if remaining <= BUDGET_FLOOR {
tracing::warn!(
host,
remaining,
floor = BUDGET_FLOOR,
resets_at,
"pausing pull request reads on this host until its rate limit resets"
);
}
self.budgets.keep(host, budget.clone());
}
}
pub(super) enum DetailError {
Paused(Budget),
Refused(String),
Failed(ReadError),
}
impl Shared {
pub(super) async fn tick(&self, now: u64) {
let mut reader = self.reader.lock().await;
let hosts = due::due(&self.state(), now);
let mut reads = Reads::default();
for (host, due) in hosts {
let Due {
plan,
mut wants_detail,
shown_branches,
} = due;
if reader.paused(&host, now).is_some() {
continue;
}
read_into(&mut reader, &host, plan, now, &mut reads).await;
wants_detail.extend(shown_branches.iter().filter_map(|branch| {
match reads.branches.get(branch)? {
Ok(Found::Pr(summary)) => Some(summary.id.clone()),
Ok(Found::None | Found::OnlyForks(_)) | Err(_) => None,
}
}));
let moved = {
let state = self.state();
let mut moved: Vec<PrId> = reads
.prs
.iter()
.filter(|(pr, _)| pr.repo.host == host && wants_detail.contains(*pr))
.filter_map(|(pr, read)| match read {
Read::Summary(summary)
if due::moved_since_detail(state.snapshots.get(pr), summary) =>
{
Some(pr.clone())
}
Read::Summary(_) | Read::Detail(_) | Read::Refused(_) | Read::Failed(_) => {
None
}
})
.collect();
moved.sort_by(due::by_number);
moved
};
let plan = FetchPlan {
details: moved,
..FetchPlan::default()
};
read_into(&mut reader, &host, plan, now, &mut reads).await;
}
let told = self.update(|state| self.apply(state, &reads, now));
drop(reader);
self.tell(told);
}
pub(super) async fn read_detail(&self, pr: &PrId, now: u64) -> Result<PrDetail, DetailError> {
let mut reader = self.reader.lock().await;
let host = pr.repo.host.as_str();
if let Some(budget) = reader.paused(host, now) {
return Err(DetailError::Paused(budget));
}
let plan = FetchPlan {
details: vec![pr.clone()],
..FetchPlan::default()
};
let mut reads = Reads::default();
read_into(&mut reader, host, plan, now, &mut reads).await;
let detail = match reads.prs.get(pr) {
Some(Read::Detail(detail)) => Ok(PrDetail::clone(detail)),
Some(Read::Refused(why)) => Err(DetailError::Refused(why.clone())),
Some(Read::Failed(error)) => Err(DetailError::Failed(error.clone())),
Some(Read::Summary(_)) | None => Err(DetailError::Failed(ReadError::Failed(format!(
"GitHub's answer left out {pr}"
)))),
};
self.keep_unjudged(reads, now);
drop(reader);
detail
}
pub(super) async fn read_branch(&self, branch: &BranchId, now: u64) -> Option<Detailed> {
let mut reader = self.reader.lock().await;
let host = branch.repo.host.as_str();
if reader.paused(host, now).is_some() {
return None;
}
let known = self.state().found(branch).cloned();
let plan = FetchPlan {
branches: vec![branch.clone()],
links: Vec::new(),
details: known.iter().cloned().collect(),
};
let mut reads = Reads::default();
read_into(&mut reader, host, plan, now, &mut reads).await;
let found = match reads.branches.get(branch) {
Some(Ok(Found::Pr(summary))) => Some(summary.id.clone()),
Some(Ok(Found::None | Found::OnlyForks(_)) | Err(_)) | None => None,
};
if let Some(pr) = found.as_ref().filter(|pr| Some(*pr) != known.as_ref()) {
let plan = FetchPlan {
details: vec![pr.clone()],
..FetchPlan::default()
};
read_into(&mut reader, host, plan, now, &mut reads).await;
}
let detail = found.and_then(|pr| match reads.prs.get(&pr) {
Some(Read::Detail(detail)) => Some(Detailed {
detail: PrDetail::clone(detail),
at: now,
}),
Some(Read::Summary(_) | Read::Refused(_) | Read::Failed(_)) | None => None,
});
self.keep_unjudged(reads, now);
drop(reader);
detail
}
fn keep_unjudged(&self, mut reads: Reads, now: u64) {
self.update(|state| {
let watched: Vec<PrId> = reads
.prs
.keys()
.filter(|pr| state.watched(pr))
.cloned()
.collect();
for pr in watched {
let Some(read) = reads.prs.remove(&pr) else {
continue;
};
let snapshot = state.snapshots.entry(pr).or_default();
match read {
Read::Summary(summary) => snapshot.saw_summary(summary, now),
Read::Detail(detail) => snapshot.saw_unjudged(*detail, now),
Read::Refused(why) => snapshot.show_failed(Trouble::Refused(why), now),
Read::Failed(error) => snapshot.show_failed(Trouble::Failed(error), now),
}
}
keep(state, &reads, now);
});
}
fn apply(&self, state: &mut State, reads: &Reads, now: u64) -> Vec<(SessionId, Arc<Notify>)> {
keep(state, reads, now);
let shown = due::shown(state, now);
let State {
sessions,
snapshots,
interest,
branches,
default_branches: _,
} = state;
let mut told = Vec::new();
for (session, entry) in sessions.iter_mut() {
let (changed, news) = evaluate(&mut entry.record, &reads.prs, now);
let has_news = !news.is_empty();
for item in news {
entry
.record
.queue_news(item, NEWS_PER_SESSION, &entry.in_flight);
}
if changed || has_news {
let _ = self.save(session, &entry.record);
}
if has_news {
told.push((session.clone(), Arc::clone(&entry.notify)));
}
}
sessions.retain(|_, entry| !entry.disposable());
branches.retain(|branch, _| {
interest
.sessions()
.any(|(_, looked)| looked.checkout().branch() == Some(branch))
});
let found: HashSet<&PrId> = branches
.values()
.filter_map(|read| match &read.found {
Some(Found::Pr(summary)) => Some(&summary.id),
Some(Found::None | Found::OnlyForks(_)) | None => None,
})
.collect();
let mut linked: HashMap<&PrId, bool> = HashMap::new();
for link in sessions.values().flat_map(|entry| entry.record.links()) {
*linked.entry(&link.pr).or_default() |= link.watch.is_some();
}
snapshots.retain(|pr, snapshot| {
let watched = linked.get(pr).copied();
if watched.is_none() && !found.contains(pr) {
return false;
}
if watched != Some(true) && !shown.contains(pr) {
snapshot.forget_details();
}
true
});
told
}
}
fn evaluate(
record: &mut SessionRecord,
reads: &HashMap<PrId, Read>,
now: u64,
) -> (bool, Vec<News>) {
let watched: Vec<PrId> = record.watching().map(|(link, _)| link.pr.clone()).collect();
let mut changed = false;
let mut news = Vec::new();
for pr in watched {
let Some(read) = reads.get(&pr) else {
continue;
};
let Some(link) = record.link_mut(&pr) else {
continue;
};
let Some(watch) = link.watch.as_ref() else {
continue;
};
let Report { changes, next, end } = match read {
Read::Summary(_) => continue,
Read::Detail(detail) => watch::evaluate(watch, detail, now),
Read::Refused(why) => watch::refused_read(watch, why),
Read::Failed(error) => watch::failed_read(watch, error),
};
changed |= end.is_some() || link.watch.as_ref() != Some(&next);
let head = next.head_oid.clone();
link.watch = if end.is_some() { None } else { Some(next) };
if !changes.is_empty() || end.is_some() {
let pushed = link
.told_head
.as_ref()
.is_some_and(|told| Some(told) != head.as_ref());
link.told_head.clone_from(&head);
let checks = match read {
Read::Detail(detail) => Some(CheckTally::of(detail)),
Read::Summary(_) | Read::Refused(_) | Read::Failed(_) => None,
};
news.push(News {
seq: 0,
pr,
url: link.url.clone(),
head,
changes,
end,
at: now,
pushed,
checks,
});
}
}
(changed, news)
}
#[cfg(test)]
#[path = "poller_tests.rs"]
mod tests;