use std::collections::HashMap; use std::future::Future; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; use std::time::Duration; use futures_util::future::select_all; use futures_util::{Stream, StreamExt, stream}; use tokio::sync::watch; use topcoat::Result; use topcoat::context::Cx; use topcoat::router::HeaderValue; use topcoat::router::content::sse::{Event, KeepAlive, Sse}; use topcoat::router::response::{IntoResponse, Response}; use crate::state::AppState; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Topic { RepoRefs(String), RepoIssues(String), Issue(String), PullList(String), Pull(String), Repo(String), User(String), Inbox(String), ReviewRequests(String), Explore, Org(String), AdminUsers, AdminUser(String), AdminAudit, AdminBackups, AdminReplication, AdminHealth, AdminServer, RepoReleases(String), Account(String), RepoSettings(String), CommitStatuses(String), ServerSettings, } pub fn admin() -> &'static LiveHub { static ADMIN: OnceLock = OnceLock::new(); ADMIN.get_or_init(LiveHub::default) } fn seq_counter() -> &'static AtomicU64 { static LIVE_SEQ: OnceLock = OnceLock::new(); LIVE_SEQ.get_or_init(|| { let start = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| u64::try_from(d.as_micros()).unwrap_or(u64::MAX / 2)); AtomicU64::new(start) }) } pub fn live_seq() -> u64 { seq_counter().load(Ordering::SeqCst) } pub fn next_live_seq() -> u64 { seq_counter().fetch_add(1, Ordering::SeqCst) + 1 } #[derive(Clone, Copy, Debug)] pub struct LiveSeq(pub u64); #[derive(Default)] pub struct LiveHub { topics: Mutex>>, } impl LiveHub { fn topics(&self) -> MutexGuard<'_, HashMap>> { self.topics.lock().unwrap_or_else(PoisonError::into_inner) } pub fn subscribe(&self, topic: &Topic) -> watch::Receiver { let mut topics = self.topics(); topics.retain(|_, tx| tx.receiver_count() > 0); topics .entry(topic.clone()) .or_insert_with(|| watch::channel(0).0) .subscribe() } pub fn bump(&self, topic: &Topic) { next_live_seq(); let mut topics = self.topics(); let Some(tx) = topics.get(topic) else { return; }; tx.send_modify(|generation| *generation = generation.wrapping_add(1)); if tx.receiver_count() == 0 { topics.remove(topic); } } pub fn bump_repo_issues(&self, repo_id: &str) { self.bump(&Topic::RepoIssues(repo_id.to_owned())); } pub fn bump_issue(&self, repo_id: &str, issue_id: &str) { self.bump(&Topic::RepoIssues(repo_id.to_owned())); self.bump(&Topic::Issue(issue_id.to_owned())); } pub fn bump_repo(&self, owner_id: &str, repo_id: &str) { self.bump(&Topic::User(owner_id.to_owned())); self.bump(&Topic::Org(owner_id.to_owned())); self.bump(&Topic::Explore); self.bump(&Topic::Repo(repo_id.to_owned())); admin().bump(&Topic::AdminUser(owner_id.to_owned())); } } struct Follow { wakes: Vec>, read: F, last: T, diff: Diff, } type Diff = fn(&T, &T) -> Option<&'static str>; fn named_event(name: &'static str, suffix: &str) -> Result { Ok(Event::new() .event(name) .data(format!("{}{suffix}", live_seq()))) } fn wake_event() -> Result { named_event("changed", "") } async fn wait_any(wakes: &mut [watch::Receiver]) -> bool { let waits = wakes.iter_mut().map(|rx| Box::pin(rx.changed())); let (woken, _, _) = select_all(waits).await; woken.is_ok() } pub fn stream_wakes(cx: &Cx, hub: &LiveHub, topics: &[Topic]) -> Result { let wakes: Vec> = topics.iter().map(|t| hub.subscribe(t)).collect(); let events = stream::unfold(wakes, |mut wakes| async move { if !wait_any(&mut wakes).await { return None; } Some((wake_event(), wakes)) }); events_response(cx, events) } pub async fn stream_changes( cx: &Cx, hub: &LiveHub, topics: &[Topic], read: F, ) -> Result where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, { stream_changes_with(cx, hub, topics, Vec::new(), read).await } pub async fn stream_changes_with( cx: &Cx, hub: &LiveHub, topics: &[Topic], extra: Vec>, read: F, ) -> Result where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, { let diff: Diff = |old, new| (old != new).then_some(""); let events = named_changes(hub, topics.to_vec(), extra, "changed", read, diff).await?; events_response(cx, events) } pub async fn stream_changes_split( cx: &Cx, hub: &LiveHub, topics: &[Topic], extra: Vec>, read: F, ) -> Result where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, { let diff: Diff<(String, String)> = |old, new| { if old.1 != new.1 { Some("") } else if old.0 != new.0 { Some(" head") } else { None } }; let events = named_changes(hub, topics.to_vec(), extra, "changed", read, diff).await?; events_response(cx, events) } async fn named_changes( hub: &LiveHub, topics: Vec, extra: Vec>, name: &'static str, read: F, diff: Diff, ) -> Result> + Send + 'static> where T: Send + 'static, F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, { let mut wakes: Vec> = topics.iter().map(|topic| hub.subscribe(topic)).collect(); wakes.extend(extra); let last = read().await?; Ok(stream::unfold( Follow { wakes, read, last, diff, }, move |mut follow| async move { loop { if !wait_any(&mut follow.wakes).await { return None; } let now = match (follow.read)().await { Ok(now) => now, Err(e) => { tracing::error!(error = %e, "live: could not read the page state"); return None; } }; let suffix = (follow.diff)(&follow.last, &now); follow.last = now; if let Some(suffix) = suffix { return Some((named_event(name, suffix), follow)); } } }, )) } pub fn bump_account(state: &AppState, user_id: &str) { state.live.bump(&Topic::Account(user_id.to_owned())); } pub fn bump_settings(hub: &LiveHub, repo_id: &str) { hub.bump(&Topic::RepoSettings(repo_id.to_owned())); } pub fn bump_pull(state: &AppState, repo_id: &str, issue_id: &str) { state.live.bump(&Topic::Pull(issue_id.to_owned())); bump_list(state, repo_id); } pub fn bump_list(state: &AppState, repo_id: &str) { state.live.bump(&Topic::PullList(repo_id.to_owned())); } pub async fn bump_repo_pulls(state: &AppState, repo_id: &str) { bump_list(state, repo_id); match state.store.pull_refs(repo_id).await { Ok(refs) => { for (issue_id, _) in refs { state.live.bump(&Topic::Pull(issue_id)); } } Err(e) => tracing::error!(error = %e, repo_id, "live: listing pulls to bump failed"), } } pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) { bump_list(state, repo_id); match state.store.pulls_for_head_oid(repo_id, sha).await { Ok(refs) => { for (issue_id, _) in refs { state.live.bump(&Topic::Pull(issue_id)); } } Err(e) => { tracing::error!(error = %e, repo_id, "live: listing pulls for a head to bump failed") } } } const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); pub type Status = Option<(String, bool)>; pub fn changed_event(status: String) -> Result { Ok(Event::new().event("changed").data(status)) } pub fn wake_stream( wake: watch::Receiver, status: &'static str, ) -> impl Stream> + Send + 'static { stream::unfold(wake, move |mut wake| async move { wake.changed().await.ok()?; Some((changed_event(status.to_owned()), wake)) }) } pub fn changed_stream( wake: watch::Receiver, only_on_status: bool, name: &'static str, read: F, ) -> impl Stream> + Send + 'static where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, { struct Follow { wake: watch::Receiver, only_on_status: bool, read: F, last: Option, done: bool, primed: bool, } stream::unfold( Follow { wake, only_on_status, read, last: None, done: false, primed: false, }, move |mut follow| async move { loop { if follow.done { return None; } if follow.primed && follow.wake.changed().await.is_err() { return None; } follow.primed = true; let (status, terminal) = match (follow.read)().await { Ok(Some(found)) => found, Ok(None) => return None, Err(e) => { tracing::error!(error = %e, "ci: live stream could not read the status"); return None; } }; follow.done = terminal; let changed = follow.last.as_deref() != Some(status.as_str()); let send = changed || !follow.only_on_status; follow.last = Some(status.clone()); if send { return Some((Ok(Event::new().event(name).data(status)), follow)); } } }, ) } const MAX_STREAMS_PER_CLIENT: usize = 64; const MAX_STREAMS: usize = 4096; static OPEN_STREAMS: Mutex<(usize, Option>)> = Mutex::new((0, None)); struct StreamSlot { ip: Option, } impl StreamSlot { fn take(cx: &Cx) -> Option { if topcoat::context::try_context::(cx).is_none() { return Some(StreamSlot { ip: None }); } let ip = crate::client_ip::client_ip(cx); let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner()); let (total, per_client) = &mut *open; let map = per_client.get_or_insert_with(HashMap::new); let count = map.get(&ip).copied().unwrap_or(0); if *total >= MAX_STREAMS || count >= MAX_STREAMS_PER_CLIENT { return None; } *map.entry(ip).or_insert(0) += 1; *total += 1; Some(StreamSlot { ip: Some(ip) }) } } impl Drop for StreamSlot { fn drop(&mut self) { let Some(ip) = self.ip else { return; }; let mut open = OPEN_STREAMS.lock().unwrap_or_else(|e| e.into_inner()); let (total, per_client) = &mut *open; *total = total.saturating_sub(1); if let Some(map) = per_client.as_mut() && let Some(count) = map.get_mut(&ip) { *count = count.saturating_sub(1); if *count == 0 { map.remove(&ip); } } } } const STREAM_RETRY: Duration = Duration::from_secs(1); pub fn events_response( cx: &Cx, events: impl Stream> + Send + 'static, ) -> Result { let Some(slot) = StreamSlot::take(cx) else { let mut res = Response::new(topcoat::router::Body::from("too many open live streams")); *res.status_mut() = http::StatusCode::TOO_MANY_REQUESTS; return Ok(res); }; let events = events.map(move |event| { let _held = &slot; event }); let retry = stream::once(std::future::ready(Ok(Event::new().retry(STREAM_RETRY)))); let events = Sse::new(retry.chain(events)).keep_alive( KeepAlive::new() .interval(STREAM_KEEP_ALIVE) .text("keepalive"), ); let mut res = events.into_response(cx)?; res.headers_mut() .insert("x-accel-buffering", HeaderValue::from_static("no")); Ok(res) } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn a_bump_wakes_only_the_subscribers_of_that_topic() { let hub = LiveHub::default(); let a = Topic::RepoRefs("repo-a".to_owned()); let b = Topic::RepoRefs("repo-b".to_owned()); let mut wake_a = hub.subscribe(&a); let wake_b = hub.subscribe(&b); hub.bump(&a); tokio::time::timeout(Duration::from_secs(1), wake_a.changed()) .await .expect("woken") .expect("open"); assert!(!wake_b.has_changed().expect("open")); } #[tokio::test] async fn a_topic_nobody_holds_is_dropped_on_the_next_change() { let hub = LiveHub::default(); let topic = Topic::RepoRefs("repo-a".to_owned()); let wake = hub.subscribe(&topic); drop(wake); hub.bump(&topic); assert!(hub.topics().is_empty()); } #[tokio::test] async fn bump_repo_wakes_the_owner_the_explore_list_and_the_repo() { let hub = LiveHub::default(); let owner = hub.subscribe(&Topic::User("owner".to_owned())); let explore = hub.subscribe(&Topic::Explore); let repo = hub.subscribe(&Topic::Repo("repo".to_owned())); let other = hub.subscribe(&Topic::User("someone".to_owned())); hub.bump_repo("owner", "repo"); assert!(owner.has_changed().expect("open")); assert!(explore.has_changed().expect("open")); assert!(repo.has_changed().expect("open")); assert!(!other.has_changed().expect("open")); } }