use std::{
collections::HashMap,
fmt,
future::Future,
path::Path,
sync::{Arc, Mutex, MutexGuard, PoisonError},
time::{SystemTime, UNIX_EPOCH},
};
use rho_sdk::SessionId;
use tokio::sync::{mpsc, Notify};
use super::{
checkout::Checkout,
due::{self, ShowOf},
gh::{Forge, ReadError},
inbox::{PullRequestError, PullRequestInbox},
interest::{Interest, Lease, Shown},
model::{BranchId, Found, PrDetail, PrId, PrSummary, RepoId},
poller::{Budgets, Reader},
record::SessionRecord,
state::News,
store::PullRequestStore,
wire,
};
#[derive(Clone)]
pub(crate) struct PullRequests(Arc<Shared>);
pub(super) struct Shared {
store: Result<PullRequestStore, String>,
state: Mutex<State>,
pub(super) reader: tokio::sync::Mutex<Reader>,
pub(super) budgets: Arc<Budgets>,
changed: Arc<Notify>,
poke: Notify,
wakes: mpsc::UnboundedSender<SessionId>,
wake_requests: Mutex<Option<mpsc::UnboundedReceiver<SessionId>>>,
merges: mpsc::UnboundedSender<AllMerged>,
merge_requests: Mutex<Option<mpsc::UnboundedReceiver<AllMerged>>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AllMerged {
pub(crate) session: SessionId,
pub(crate) at: u64,
}
#[derive(Default)]
pub(super) struct Applied {
pub(super) told: Vec<Told>,
pub(super) all_merged: Vec<AllMerged>,
}
pub(super) struct Told {
pub(super) session: SessionId,
pub(super) notify: Arc<Notify>,
}
#[derive(Default)]
pub(super) struct State {
pub(super) sessions: HashMap<SessionId, Entry>,
pub(super) snapshots: HashMap<PrId, Snapshot>,
pub(super) interest: Interest,
pub(super) branches: HashMap<BranchId, BranchRead>,
pub(super) default_branches: HashMap<RepoId, DefaultBranch>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct DefaultBranch {
pub(super) name: Option<String>,
pub(super) at: u64,
}
impl State {
pub(super) fn entry(&mut self, session: &SessionId) -> &mut Entry {
self.sessions
.entry(session.clone())
.or_insert_with(|| Entry::new(SessionRecord::default()))
}
pub(super) fn found(&self, branch: &BranchId) -> Option<&PrId> {
match self.branches.get(branch)?.found.as_ref()? {
Found::Pr(summary) => Some(&summary.id),
Found::None | Found::OnlyForks(_) => None,
}
}
pub(super) fn recheck_branch(&mut self, session: &SessionId, pr: &PrId) {
let Some(branch) = self
.interest
.session(session)
.and_then(|interest| interest.checkout().branch())
else {
return;
};
if branch.repo != pr.repo || self.found(branch) == Some(pr) {
return;
}
if let Some(read) = self.branches.get_mut(branch) {
read.asked_at = None;
}
}
pub(super) fn is_default(&self, branch: &BranchId) -> bool {
self.default_seen_at(branch).is_some()
}
pub(super) fn default_seen_at(&self, branch: &BranchId) -> Option<u64> {
let default = self.default_branches.get(&branch.repo)?;
(default.name.as_deref() == Some(branch.branch.as_str())).then_some(default.at)
}
pub(super) fn watched(&self, pr: &PrId) -> bool {
self.sessions
.values()
.any(|entry| entry.record.watching().any(|(link, _)| link.pr == *pr))
}
}
pub(super) struct Entry {
pub(super) record: SessionRecord,
pub(super) in_flight: Vec<u64>,
pub(super) notify: Arc<Notify>,
pub(super) merge_told: Option<u64>,
}
impl Entry {
pub(super) fn new(record: SessionRecord) -> Self {
Self {
record,
in_flight: Vec::new(),
notify: Arc::new(Notify::new()),
merge_told: None,
}
}
pub(super) fn waiting(&self) -> impl Iterator<Item = &News> + '_ {
self.record
.news()
.iter()
.filter(|news| !self.in_flight.contains(&news.seq))
}
pub(super) fn release(&mut self, seqs: &[u64]) {
self.in_flight.retain(|seq| !seqs.contains(seq));
}
pub(super) fn disposable(&self) -> bool {
self.record.is_empty()
&& self.record.news_generation() == 0
&& Arc::strong_count(&self.notify) == 1
}
}
#[derive(Default)]
pub(super) struct Snapshot {
pub(super) summary: Option<PrSummary>,
pub(super) detail: Option<Detailed>,
pub(super) unjudged: Option<Detailed>,
pub(super) read_at: Option<u64>,
pub(super) asked_at: Option<u64>,
pub(super) show_failed_at: Option<u64>,
pub(super) trouble: Option<Trouble>,
}
#[derive(Debug, Default)]
pub(super) struct BranchRead {
pub(super) found: Option<Found>,
pub(super) asked_at: Option<u64>,
pub(super) trouble: Option<Trouble>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Trouble {
Refused(String),
Failed(ReadError),
}
impl fmt::Display for Trouble {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Refused(why) => formatter.write_str(why),
Self::Failed(error) => write!(formatter, "{error}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Detailed {
pub(crate) detail: PrDetail,
pub(crate) at: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ShowRead {
Cached,
Fresh,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ShowTarget {
Branch,
Linked(PrId),
}
impl Snapshot {
pub(super) fn saw_summary(&mut self, summary: PrSummary, now: u64) {
self.summary = Some(summary);
self.read_at = Some(now);
self.trouble = None;
}
pub(super) fn saw_detail(&mut self, detail: PrDetail, now: u64) {
self.saw_summary(detail.summary.clone(), now);
self.detail = Some(Detailed { detail, at: now });
if self
.unjudged
.as_ref()
.is_some_and(|unjudged| unjudged.at <= now)
{
self.unjudged = None;
}
}
pub(super) fn saw_unjudged(&mut self, detail: PrDetail, now: u64) {
self.saw_summary(detail.summary.clone(), now);
self.unjudged = Some(Detailed { detail, at: now });
}
pub(super) fn newest_detail(&self) -> Option<&Detailed> {
match (&self.detail, &self.unjudged) {
(Some(judged), Some(unjudged)) if unjudged.at >= judged.at => Some(unjudged),
(Some(judged), _) => Some(judged),
(None, unjudged) => unjudged.as_ref(),
}
}
pub(super) fn answer(&self) -> Option<&Detailed> {
self.newest_detail().filter(|detailed| {
self.summary
.as_ref()
.is_none_or(|summary| due::reads_as(&detailed.detail.summary, summary))
})
}
pub(super) fn show_failed(&mut self, trouble: Trouble, now: u64) {
self.trouble = Some(trouble);
self.show_failed_at = Some(now);
}
pub(super) fn forget_details(&mut self) {
self.detail = None;
self.unjudged = None;
}
}
impl Shared {
pub(super) fn state(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(super) fn update<T>(&self, change: impl FnOnce(&mut State) -> T) -> T {
let changed = change(&mut self.state());
self.changed.notify_waiters();
changed
}
pub(super) fn store(&self) -> Result<&PullRequestStore, PullRequestError> {
self.store
.as_ref()
.map_err(|cause| PullRequestError::Store(cause.clone()))
}
pub(super) fn save(&self, session: &SessionId, record: &SessionRecord) -> Result<(), String> {
let store = self.store.as_ref().map_err(Clone::clone)?;
store.save(session, record).map_err(|error| {
tracing::warn!(%session, %error, "could not save the session's pull request record");
format!("could not save this session's pull request record: {error}")
})
}
pub(super) fn tell(&self, applied: Applied) {
let Applied { told, all_merged } = applied;
for merged in all_merged {
let _ = self.merges.send(merged);
}
for Told { session, notify } in told {
notify.notify_waiters();
let _ = self.wakes.send(session);
}
}
fn leased(&self, lease: Lease) {
match lease {
Lease::New => self.poke.notify_one(),
Lease::Renewed => {}
}
}
pub(super) fn poke_if_leased(&self, state: &State, session: &SessionId, now: u64) {
if state.interest.leased(session, now) {
self.poke.notify_one();
}
}
}
impl PullRequests {
pub(crate) fn open(state_dir: &Path, forge: Arc<dyn Forge>) -> Self {
let (store, records) = match PullRequestStore::open(state_dir) {
Ok(store) => {
let records = store.load_all();
(Ok(store), records)
}
Err(error) => {
let dir = state_dir.display();
tracing::warn!(%dir, %error, "could not open the pull request records");
let cause = format!("could not open rho's pull request records in {dir}: {error}");
(Err(cause), Vec::new())
}
};
let sessions = records
.into_iter()
.map(|(session, record)| (session, Entry::new(record)))
.collect();
let (wakes, wake_requests) = mpsc::unbounded_channel();
let (merges, merge_requests) = mpsc::unbounded_channel();
let budgets = Arc::new(Budgets::default());
Self(Arc::new(Shared {
store,
state: Mutex::new(State {
sessions,
..State::default()
}),
reader: tokio::sync::Mutex::new(Reader::new(forge, Arc::clone(&budgets))),
budgets,
changed: Arc::new(Notify::new()),
poke: Notify::new(),
wakes,
wake_requests: Mutex::new(Some(wake_requests)),
merges,
merge_requests: Mutex::new(Some(merge_requests)),
}))
}
pub(crate) fn inbox(&self, session: &SessionId, cwd: &Path) -> PullRequestInbox {
PullRequestInbox::new(Arc::clone(&self.0), session.clone(), cwd.to_owned())
}
pub(crate) async fn run(&self, stopping: impl Future<Output = ()>) {
tokio::pin!(stopping);
loop {
let period = due::tick_period(&self.0.state(), unix_ms());
tokio::select! {
() = &mut stopping => return,
() = tokio::time::sleep(period) => {}
() = self.0.poke.notified() => {}
}
tokio::select! {
() = &mut stopping => return,
() = self.tick(unix_ms()) => {}
}
}
}
pub(crate) async fn tick(&self, now: u64) {
self.0.tick(now).await;
}
pub(crate) fn take_wake_requests(&self) -> Option<mpsc::UnboundedReceiver<SessionId>> {
self.0
.wake_requests
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
}
pub(crate) fn take_all_merged(&self) -> Option<mpsc::UnboundedReceiver<AllMerged>> {
self.0
.merge_requests
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
}
pub(crate) fn request_wake(&self, session: &SessionId) {
let _ = self.0.wakes.send(session.clone());
}
pub(crate) fn news_generation(&self, session: &SessionId) -> u64 {
self.0
.state()
.sessions
.get(session)
.map_or(0, |entry| entry.record.news_generation())
}
pub(crate) fn sessions(&self) -> Vec<SessionId> {
self.0.state().sessions.keys().cloned().collect()
}
pub(crate) fn watches(&self, session: &SessionId) -> bool {
self.0
.state()
.sessions
.get(session)
.is_some_and(|entry| entry.record.watching().next().is_some())
}
pub(crate) fn has_news(&self, session: &SessionId) -> bool {
self.0
.state()
.sessions
.get(session)
.is_some_and(|entry| entry.waiting().next().is_some())
}
pub(crate) fn list(&self, session: &SessionId, checkout: Checkout, now: u64) {
let lease = self
.0
.update(|state| state.interest.list(session, checkout, now));
self.0.leased(lease);
}
pub(crate) async fn show(
&self,
session: &SessionId,
checkout: Checkout,
target: ShowTarget,
read: ShowRead,
now: u64,
) -> Result<Option<Detailed>, PullRequestError> {
let shown =
match target {
ShowTarget::Branch => Shown::Branch,
ShowTarget::Linked(pr) => {
let linked =
self.0.state().sessions.get(session).is_some_and(|entry| {
entry.record.links().iter().any(|link| link.pr == pr)
});
if !linked {
return Err(PullRequestError::InvalidTarget(format!(
"{pr} is not linked to this session"
)));
}
Shown::Linked(pr)
}
};
let of = match (&shown, checkout.branch()) {
(Shown::Linked(pr), _) => Some(ShowOf::Linked(pr)),
(Shown::Branch, Some(branch)) => Some(ShowOf::Branch(branch)),
(Shown::Branch, None) => None,
};
let reads = of.is_some_and(|of| due::show_reads(&self.0.state(), of, read, now));
let fresh = match of {
Some(ShowOf::Linked(pr)) if reads => self
.0
.read_detail(pr, now)
.await
.ok()
.map(|detail| Detailed { detail, at: now }),
Some(ShowOf::Branch(branch)) if reads => self.0.read_branch(branch, now).await,
Some(ShowOf::Linked(_) | ShowOf::Branch(_)) | None => None,
};
let detail = match (fresh, of) {
(Some(fresh), _) => Some(fresh),
(None, Some(of)) => kept_detail(&self.0.state(), of),
(None, None) => None,
};
let lease = self
.0
.update(|state| state.interest.show(session, checkout, shown, now));
self.0.leased(lease);
Ok(detail)
}
pub(crate) fn changes(&self) -> impl Future<Output = ()> + Send + 'static {
Arc::clone(&self.0.changed).notified_owned()
}
pub(crate) fn view(&self, session: &SessionId, now: u64) -> rho_protocol::SessionPullRequests {
let budgets = &self.0.budgets;
wire::session(&self.0.state(), |host| budgets.paused(host, now), session)
}
pub(crate) fn forget(&self, session: &SessionId) {
let mut state = self.0.state();
state.sessions.remove(session);
state.interest.forget(session);
if let Ok(store) = &self.0.store {
if let Err(error) = store.forget(session) {
tracing::warn!(%session, %error, "could not delete the session's pull request record");
}
}
}
}
fn kept_detail(state: &State, of: ShowOf<'_>) -> Option<Detailed> {
let pr = match of {
ShowOf::Linked(pr) => pr,
ShowOf::Branch(branch) => state.found(branch)?,
};
state.snapshots.get(pr)?.answer().cloned()
}
impl fmt::Debug for PullRequests {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PullRequests")
.finish_non_exhaustive()
}
}
pub(crate) fn unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| {
u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
})
}