use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::response::Response; use topcoat::router::{path_param, route}; use crate::live::{LiveHub, Topic, stream_wakes}; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; path_param!(owner); path_param!(repo); pub fn live_url(owner: &str, repo: &str) -> String { format!("/{owner}/{repo}/refs/events") } pub fn topics(repo: &forge_core::Repo) -> [Topic; 3] { [ Topic::Repo(repo.id.clone()), Topic::RepoRefs(repo.id.clone()), Topic::CommitStatuses(repo.id.clone()), ] } #[route(GET "/{owner}/{repo}/refs/events")] async fn ref_events(cx: &Cx) -> Result { let owner = owner(cx); let name = repo(cx); let ctx = load_repo(cx, owner, name).await?; let hub: &LiveHub = &context::(cx).live; stream_wakes(cx, hub, &topics(&ctx.repo)) } #[cfg(test)] mod tests { use std::time::Duration; use forge_core::Visibility; use topcoat::router::Body; use topcoat::router::request::Request; use crate::live::Topic; use crate::test_support::fixture::{Fixture, OWNER, REPO}; async fn open(fx: &Fixture, path: &str) -> topcoat::router::response::Response { let req = Request::builder() .method("GET") .uri(path) .body(Body::empty()) .unwrap(); fx.router.handle(req).await } #[tokio::test] async fn a_ref_write_or_a_status_wakes_the_stream() { use futures_util::StreamExt; let fx = Fixture::new(Visibility::Public).await; let repo = fx .store .repo_by_owner_and_name(OWNER, REPO) .await .unwrap() .unwrap(); let res = open(&fx, &format!("/{OWNER}/{REPO}/refs/events")).await; assert_eq!(res.status().as_u16(), 200); assert_eq!( res.headers().get("content-type").unwrap(), "text/event-stream" ); let mut frames = res.into_body().into_data_stream(); let retry = frames.next().await.expect("a frame").expect("data"); assert!(retry.starts_with(b"retry: 1000"), "{retry:?}"); fx.live.bump(&Topic::RepoRefs(repo.id.clone())); let first = tokio::time::timeout(Duration::from_secs(5), frames.next()) .await .expect("woken") .expect("a frame") .expect("data"); assert_eq!(&first[..], b"event: changed\ndata: 1\n\n"); fx.live.bump(&Topic::CommitStatuses(repo.id.clone())); let second = tokio::time::timeout(Duration::from_secs(5), frames.next()) .await .expect("woken") .expect("a frame") .expect("data"); assert_eq!(&second[..], b"event: changed\ndata: 1\n\n"); } #[tokio::test] async fn a_private_repo_stream_is_404_for_anonymous() { let fx = Fixture::new(Visibility::Private).await; let res = open(&fx, &format!("/{OWNER}/{REPO}/refs/events")).await; assert_eq!(res.status().as_u16(), 404); } #[tokio::test] async fn an_unknown_repo_stream_is_404() { let fx = Fixture::new(Visibility::Public).await; let res = open(&fx, &format!("/{OWNER}/nope/refs/events")).await; assert_eq!(res.status().as_u16(), 404); } }