use std::{
collections::HashMap,
fmt,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use rho_sdk::SessionId;
use super::{
checkout::origin,
gh::ReadError,
model::{Mergeable, PrDetail, PrId, PrState, Rollup, ThreadState, GITHUB},
news,
poller::{DetailError, BUDGET_FLOOR, WATCHES_PER_SESSION},
record::{LinkOrigin, Stood},
service::{Entry, Shared},
state::{CheckTally, End, Gate, News, WatchState},
watch,
};
#[derive(Clone)]
pub(crate) struct PullRequestInbox {
shared: Arc<Shared>,
session: SessionId,
cwd: PathBuf,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct NewsBatch {
pub(crate) news: Vec<News>,
pub(crate) dropped: u32,
}
impl NewsBatch {
pub(crate) fn is_empty(&self) -> bool {
self.news.is_empty()
}
pub(crate) fn prompt(&self) -> String {
news::prompt(&self.news, self.dropped)
}
fn seqs(&self) -> Vec<u64> {
self.news.iter().map(|news| news.seq).collect()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Watched {
pub(crate) pr: PrId,
pub(crate) url: String,
pub(crate) state: PrState,
pub(crate) head: String,
pub(crate) checks: CheckCounts,
pub(crate) gate: Gate,
pub(crate) gate_checks: u32,
pub(crate) mergeable: Mergeable,
pub(crate) comments: u32,
pub(crate) unresolved_threads: u32,
pub(crate) started: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct CheckCounts {
pub(crate) total: u32,
pub(crate) passed: u32,
pub(crate) running: u32,
pub(crate) failed: u32,
pub(crate) queued_workflows: u32,
pub(crate) unread_suites: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Unwatched {
pub(crate) pr: PrId,
pub(crate) was_watched: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Linked {
pub(crate) pr: PrId,
pub(crate) url: String,
pub(crate) new: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Unlinked {
pub(crate) pr: PrId,
pub(crate) was_linked: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ListedPullRequest {
pub(crate) pr: PrId,
pub(crate) url: String,
pub(crate) origin: LinkOrigin,
pub(crate) watched: bool,
pub(crate) last_read: Option<LastRead>,
pub(crate) trouble: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct LastRead {
pub(crate) state: PrState,
pub(crate) rollup: Rollup,
pub(crate) age: Duration,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum PullRequestError {
#[error("the pull request is already {}, so there is nothing to watch; it stays linked to this session", .state.word())]
AlreadyEnded { state: PrState },
#[error("gh, GitHub's CLI, is not installed on the daemon's machine; install it and sign in with `gh auth login`, then try again")]
NotInstalled,
#[error("gh on the daemon's machine is not signed in to {host}; run `gh auth login --hostname {host}` there, then try again")]
SignedOut { host: String },
#[error("GitHub allows this account {remaining} more points until {}, at or below rho's floor of {floor}; try again then", reset_time(.resets_at))]
Budget {
remaining: u32,
floor: u32,
resets_at: i64,
},
#[error("this session would watch {asked} pull requests, over its limit of {limit}; call unwatch_pull_request on one first")]
TooManyWatches { limit: usize, asked: usize },
#[error("{0}")]
NotFound(String),
#[error("{0}")]
InvalidTarget(String),
#[error("could not read the pull request: {0}")]
Read(String),
#[error("{0}")]
Store(String),
}
impl PullRequestInbox {
pub(super) fn new(shared: Arc<Shared>, session: SessionId, cwd: PathBuf) -> Self {
Self {
shared,
session,
cwd,
}
}
pub(crate) fn has_news(&self) -> bool {
self.shared
.state()
.sessions
.get(&self.session)
.is_some_and(|entry| entry.waiting().next().is_some())
}
pub(crate) fn news_owned(&self) -> impl std::future::Future<Output = ()> + Send + 'static {
let mut state = self.shared.state();
Arc::clone(&state.entry(&self.session).notify).notified_owned()
}
pub(crate) fn take_news(&self) -> NewsBatch {
let mut state = self.shared.state();
let Some(entry) = state.sessions.get_mut(&self.session) else {
return NewsBatch::default();
};
let news: Vec<News> = entry.waiting().cloned().collect();
if news.is_empty() {
return NewsBatch::default();
}
entry.in_flight.extend(news.iter().map(|news| news.seq));
NewsBatch {
news,
dropped: entry.record.news_dropped(),
}
}
pub(crate) fn restore_news(&self, batch: &NewsBatch) {
if batch.is_empty() {
return;
}
let notify = {
let mut state = self.shared.state();
let Some(entry) = state.sessions.get_mut(&self.session) else {
return;
};
entry.release(&batch.seqs());
Arc::clone(&entry.notify)
};
notify.notify_waiters();
}
pub(crate) fn acknowledge(&self, batch: &NewsBatch) {
if batch.is_empty() {
return;
}
let mut state = self.shared.state();
let Some(entry) = state.sessions.get_mut(&self.session) else {
return;
};
let seqs = batch.seqs();
entry.release(&seqs);
entry.record.acknowledge(&seqs);
let merged = batch
.news
.iter()
.filter(|news| matches!(news.end, Some(End::Merged { .. })))
.map(|news| news.at)
.max();
if merged.is_some() {
entry.merge_told = merged;
}
let _ = self.shared.save(&self.session, &entry.record);
}
pub(crate) fn take_merge_told(&self) -> Option<u64> {
let mut state = self.shared.state();
let entry = state.sessions.get_mut(&self.session)?;
let told = entry.merge_told.take()?;
entry.record.all_merged().then_some(told)
}
pub(crate) async fn watch(&self, target: &str, now: u64) -> Result<Watched, PullRequestError> {
self.shared.store()?;
let pr = resolve_pull_request(target, &self.cwd).await?;
let known = {
let state = self.shared.state();
let watching = self.watching(&state.sessions, &pr)?;
let snapshot = state.snapshots.get(&pr);
watching.then(|| snapshot.and_then(|s| s.newest_detail().map(|d| d.detail.clone())))
};
if let Some(Some(detail)) = known {
return Ok(Watched::of(&detail, false));
}
let detail = self
.shared
.read_detail(&pr, now)
.await
.map_err(|error| refusal(error, &pr.repo.host))?;
let ended = matches!(detail.summary.state, PrState::Merged | PrState::Closed);
let started = self.shared.update(|state| {
let watching = self.watching(&state.sessions, &pr)?;
let entry = state.entry(&self.session);
let url = detail.summary.url.clone();
let linked = entry
.record
.link(pr.clone(), url, LinkOrigin::Agent, now / 1000);
let started = !watching && !ended;
if started {
if let Some(link) = entry.record.link_mut(&pr) {
let baseline = watch::evaluate(&WatchState::new(now), &detail, now);
link.watch = Some(baseline.next);
link.told_head = Some(detail.summary.change.head_oid.clone());
link.stood = Some(Stood::Open);
}
}
if linked || started {
let _ = self.shared.save(&self.session, &entry.record);
state.recheck_branch(&self.session, &pr);
self.shared.poke_if_leased(state, &self.session, now);
}
Ok::<_, PullRequestError>(started)
})?;
if ended {
return Err(PullRequestError::AlreadyEnded {
state: detail.summary.state,
});
}
Ok(Watched::of(&detail, started))
}
pub(crate) async fn unwatch(&self, target: &str) -> Result<Unwatched, PullRequestError> {
self.shared.store()?;
let pr = resolve_pull_request(target, &self.cwd).await?;
let was_watched = self.shared.update(|state| {
let Some(entry) = state.sessions.get_mut(&self.session) else {
return false;
};
let was_watched = entry
.record
.link_mut(&pr)
.and_then(|link| link.watch.take())
.is_some();
if was_watched {
let _ = self.shared.save(&self.session, &entry.record);
}
was_watched
});
Ok(Unwatched { pr, was_watched })
}
pub(crate) async fn link(
&self,
target: &str,
origin: LinkOrigin,
now: u64,
) -> Result<Linked, PullRequestError> {
self.shared.store()?;
let pr = resolve_pull_request(target, &self.cwd).await?;
let url = pr.url();
let new = self.shared.update(|state| {
let entry = state.entry(&self.session);
let mut record = entry.record.clone();
let new = record.link(pr.clone(), url.clone(), origin, now / 1000);
if new {
self.shared
.save(&self.session, &record)
.map_err(PullRequestError::Store)?;
entry.record = record;
state.recheck_branch(&self.session, &pr);
self.shared.poke_if_leased(state, &self.session, now);
}
Ok::<_, PullRequestError>(new)
})?;
Ok(Linked { pr, url, new })
}
pub(crate) async fn unlink(&self, target: &str) -> Result<Unlinked, PullRequestError> {
self.shared.store()?;
let pr = resolve_pull_request(target, &self.cwd).await?;
let was_linked = self.shared.update(|state| {
let Some(entry) = state.sessions.get_mut(&self.session) else {
return Ok(false);
};
let mut record = entry.record.clone();
let was_linked = record.unlink(&pr);
if was_linked {
self.shared
.save(&self.session, &record)
.map_err(PullRequestError::Store)?;
entry.record = record;
}
Ok::<_, PullRequestError>(was_linked)
})?;
Ok(Unlinked { pr, was_linked })
}
pub(crate) fn list(&self, now: u64) -> Vec<ListedPullRequest> {
let state = self.shared.state();
let Some(entry) = state.sessions.get(&self.session) else {
return Vec::new();
};
entry
.record
.links()
.iter()
.map(|link| {
let snapshot = state.snapshots.get(&link.pr);
let last_read = snapshot.and_then(|snapshot| {
let summary = snapshot.summary.as_ref()?;
Some(LastRead {
state: summary.state,
rollup: summary.change.rollup,
age: Duration::from_millis(now.saturating_sub(snapshot.read_at?)),
})
});
ListedPullRequest {
pr: link.pr.clone(),
url: link.url.clone(),
origin: link.origin,
watched: link.watch.is_some(),
last_read,
trouble: snapshot
.and_then(|snapshot| snapshot.trouble.as_ref())
.map(ToString::to_string),
}
})
.collect()
}
fn watching(
&self,
sessions: &HashMap<SessionId, Entry>,
pr: &PrId,
) -> Result<bool, PullRequestError> {
let Some(entry) = sessions.get(&self.session) else {
return Ok(false);
};
if entry.record.watching().any(|(link, _)| link.pr == *pr) {
return Ok(true);
}
let asked = entry.record.watching().count() + 1;
if asked > WATCHES_PER_SESSION {
return Err(PullRequestError::TooManyWatches {
limit: WATCHES_PER_SESSION,
asked,
});
}
Ok(false)
}
}
pub(crate) async fn resolve_pull_request(
target: &str,
workspace: &Path,
) -> Result<PrId, PullRequestError> {
let pr = match PrId::parse(target, None) {
Ok(pr) if pr.repo.host == GITHUB => return Ok(pr),
Ok(pr) => pr,
Err(_) => {
let origin = origin(workspace).await;
return PrId::parse(target, origin.as_ref())
.map_err(|why| PullRequestError::InvalidTarget(why.to_owned()));
}
};
if origin(workspace)
.await
.is_some_and(|origin| origin.host == pr.repo.host)
{
return Ok(pr);
}
Err(PullRequestError::InvalidTarget(format!(
"rho only reads pull requests on {GITHUB} or this workspace's origin host, not {}",
pr.repo.host
)))
}
impl fmt::Debug for PullRequestInbox {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PullRequestInbox")
.field("session", &self.session)
.finish_non_exhaustive()
}
}
impl Watched {
fn of(detail: &PrDetail, started: bool) -> Self {
let tally = CheckTally::of(detail);
let checks = CheckCounts {
total: detail.checks_total,
passed: tally.passed,
running: tally.running,
failed: tally.failed,
queued_workflows: tally.queued_workflows,
unread_suites: detail.unread_suites,
};
let (gate, gate_checks) = match watch::gate_of(&detail.checks) {
(Gate::All, _) => (Gate::All, detail.checks_total),
(Gate::Required, required) => (
Gate::Required,
u32::try_from(required.len()).unwrap_or(u32::MAX),
),
};
let thread_comments = detail.threads.iter().map(|thread| {
u32::try_from(thread.comments.len())
.unwrap_or(u32::MAX)
.saturating_add(thread.more_comments)
});
let comments = u32::try_from(detail.posts.len())
.unwrap_or(u32::MAX)
.saturating_add(detail.older_posts)
.saturating_add(thread_comments.fold(0, u32::saturating_add));
Self {
pr: detail.summary.id.clone(),
url: detail.summary.url.clone(),
state: detail.summary.state,
head: detail.summary.change.head_oid.clone(),
checks,
gate,
gate_checks,
mergeable: detail.mergeable,
comments,
unresolved_threads: u32::try_from(
detail
.threads
.iter()
.filter(|thread| thread.state != ThreadState::Resolved)
.count(),
)
.unwrap_or(u32::MAX),
started,
}
}
}
fn refusal(error: DetailError, host: &str) -> PullRequestError {
match error {
DetailError::Paused(budget) => PullRequestError::Budget {
remaining: budget.remaining,
floor: BUDGET_FLOOR,
resets_at: budget.resets_at,
},
DetailError::Refused(why) => PullRequestError::NotFound(why),
DetailError::Failed(ReadError::NotInstalled(_)) => PullRequestError::NotInstalled,
DetailError::Failed(ReadError::SignedOut(_)) => PullRequestError::SignedOut {
host: host.to_owned(),
},
DetailError::Failed(ReadError::Failed(why)) => PullRequestError::Read(why),
}
}
fn reset_time(resets_at: &i64) -> String {
chrono::DateTime::from_timestamp(*resets_at, 0).map_or_else(
|| format!("unix time {resets_at}"),
|at| at.format("%Y-%m-%d %H:%M UTC").to_string(),
)
}