use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use izumi::refresh::{LiveStore, StopFlag, spawn_interval_refresh};
use metsuke::{Forge, Involvement, PrSummary};
use tokio::sync::watch;
pub const DEFAULT_POLL: Duration = Duration::from_secs(60);
pub const DEFAULT_LIMIT: usize = 50;
pub struct PrFeed {
store: Arc<LiveStore<Vec<PrSummary>>>,
rx: watch::Receiver<u64>,
stop: StopFlag,
faulted: Arc<AtomicBool>,
}
impl PrFeed {
#[must_use]
pub fn start<F>(forge: Arc<F>, lane: Involvement, limit: usize, interval: Duration) -> Self
where
F: Forge + Send + Sync + 'static,
{
let store = LiveStore::new(Vec::<PrSummary>::new());
let rx = store.subscribe();
let stop: StopFlag = Arc::new(AtomicBool::new(false));
let faulted = Arc::new(AtomicBool::new(false));
let sink_store = Arc::clone(&store);
let panic_flag = Arc::clone(&faulted);
spawn_interval_refresh(
interval,
Arc::clone(&stop),
Arc::new(move || forge.search(lane, limit).ok()),
move |rows: Option<Vec<PrSummary>>| {
if let Some(rows) = rows {
sink_store.push(rows);
}
},
move || panic_flag.store(true, Ordering::SeqCst),
);
Self {
store,
rx,
stop,
faulted,
}
}
pub async fn changed(&self) {
let mut rx = self.rx.clone();
let _ = rx.changed().await;
}
#[must_use]
pub fn rows(&self) -> Vec<PrSummary> {
self.store.snapshot()
}
#[must_use]
pub fn faulted(&self) -> bool {
self.faulted.load(Ordering::SeqCst)
}
#[must_use]
pub fn generation(&self) -> u64 {
self.store.generation()
}
}
impl Drop for PrFeed {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
}
}