forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

code_live.rs244 lines, 9.2 KiBHistoryRawDownload
1//! Live stream of a repo's pages, at `/{owner}/{repo}/events`. The repo header renders `data-live`
2//! with this URL on every repo page (see `repo::repo_head`). A code view adds its branch to the
3//! URL. The stream sends `changed` when the header changes: stars, watchers, forks, the repo's
4//! name, description, visibility, archived flag or default branch, the open issue and pull counts,
5//! the discussions and wiki switches, the viewer's own watch level, or the mirror's last sync. The
6//! header follows the repo's issues and pulls, so an issue or pull opened or closed shows at once.
7//! On a code view of a branch it also sends `changed` when the branch moves, or when a branch or
8//! tag is created or deleted (the ref selector and the branch list depend on that). Moves of other
9//! refs send nothing. Commits and tags are not followed: they do not move.
10//!
11//! The repo home page (`home_live_url`) also follows the releases, and sends `changed` when the
12//! latest release or the linked packages' versions change. Other repo pages do not read those.
13
14use std::path::PathBuf;
15
16use forge_core::{Repo as RepoRecord, User, Visibility};
17use forge_git::browse::{RefInfo, RefKind};
18use topcoat::Result;
19use topcoat::context::{Cx, context};
20use topcoat::router::response::Response;
21use topcoat::router::{path_param, query_params, route};
22
23use crate::auth::percent_encode;
24use crate::live::{Topic, stream_changes_with};
25use crate::pages::packages::repo_package_links;
26use crate::pages::refs::load_refs;
27use crate::pages::repo_ctx::{fork_count, load_repo};
28use crate::pages::repo_side::runs_fingerprint;
29use crate::state::AppState;
30
31path_param!(owner);
32path_param!(repo);
33
34#[query_params(error = bad_request)]
35struct LiveQuery {
36 ref_name: Option<String>,
37 home: Option<String>,
38}
39
40/// Whether a code view of `ref_name` follows the branch: the ref is a branch of the repo.
41pub fn follows_branch(refs: &[RefInfo], ref_name: &str) -> bool {
42 refs.iter()
43 .any(|r| r.kind == RefKind::Branch && r.name == ref_name)
44}
45
46/// The stream URL of a code view that follows `branch`, whether or not the branch exists yet.
47pub fn branch_live_url(owner: &str, repo: &str, branch: &str) -> String {
48 format!("/{owner}/{repo}/events?ref_name={}", percent_encode(branch))
49}
50
51/// The stream URL of the repo home page: the branch's stream, which also follows the releases and
52/// the linked packages.
53pub fn home_live_url(owner: &str, repo: &str, branch: &str) -> String {
54 format!("{}&home=1", branch_live_url(owner, repo, branch))
55}
56
57/// The stream URL of a repo page. A code view of a branch adds the branch to it.
58pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String {
59 if follows_branch(refs, ref_name) {
60 branch_live_url(owner, repo, ref_name)
61 } else {
62 format!("/{owner}/{repo}/events")
63 }
64}
65
66/// The state the code view shows: every branch and tag name, and the commit `branch` points at.
67/// A move of another branch leaves it unchanged.
68async fn refs_fingerprint(path: PathBuf, branch: String) -> Result<String> {
69 let refs = load_refs(path).await?;
70 let mut names: Vec<String> = refs
71 .iter()
72 .map(|r| format!("{} {}", r.kind == RefKind::Branch, r.name))
73 .collect();
74 names.sort();
75 let at = refs
76 .iter()
77 .find(|r| r.kind == RefKind::Branch && r.name == branch)
78 .map_or("", |r| r.target.as_str());
79 Ok(format!("{}\n{at}", names.join("\n")))
80}
81
82/// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the
83/// stream then sends `changed` once and the page's own re-read shows the 404. `viewer_id` is the
84/// signed-in viewer, whose watch level the header shows.
85async fn header_fingerprint(
86 state: &AppState,
87 repo_id: &str,
88 viewer_id: Option<&str>,
89) -> Result<String> {
90 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
91 return Ok(String::new());
92 };
93 let stars = state.store.star_count(repo_id).await?;
94 let watchers = state.store.watcher_count(repo_id).await?;
95 let forks = fork_count(state, repo_id).await?;
96 let (open_issues, _) = state.store.issue_counts(repo_id).await?;
97 let (open_pulls, _) = state.store.pull_counts(repo_id).await?;
98 let discussions = state.store.discussions_enabled(repo_id).await?;
99 let wiki = state.store.wiki_enabled(repo_id).await?;
100 let watch = match viewer_id {
101 Some(viewer) => format!("{:?}", state.store.watch_level(viewer, repo_id).await?),
102 None => String::new(),
103 };
104 let mirror = match state.store.pull_mirror(repo_id).await? {
105 Some(m) => format!(
106 "{} {} {:?}",
107 m.url,
108 m.last_sync_at.as_deref().unwrap_or(""),
109 m.last_ok
110 ),
111 None => String::new(),
112 };
113 Ok(header_text(
114 &repo,
115 [stars, watchers, forks, open_issues, open_pulls],
116 &format!("{discussions} {wiki} {watch}\n{mirror}"),
117 ))
118}
119
120/// Joins the header's fields into the fingerprint text.
121fn header_text(repo: &RepoRecord, counts: [u64; 5], rest: &str) -> String {
122 let public = repo.visibility == Visibility::Public;
123 let [stars, watchers, forks, issues, pulls] = counts;
124 format!(
125 "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks} {issues} {pulls} {} {}\n{rest}",
126 repo.owner_name, repo.name, repo.description, repo.archived, repo.default_branch
127 )
128}
129
130/// The state the home page's latest release and linked-package card show.
131async fn home_fingerprint(
132 state: &AppState,
133 repo_id: &str,
134 viewer: Option<&User>,
135) -> Result<String> {
136 let mut release_text = String::new();
137 if let Some(release) = state.store.latest_release(repo_id).await? {
138 let assets = state.store.list_release_assets(&release.id).await?;
139 let names: Vec<String> = assets
140 .iter()
141 .map(|asset| format!("{} {}", asset.id, asset.name))
142 .collect();
143 release_text = format!(
144 "{} {} {} {} {}",
145 release.id,
146 release.tag,
147 release.title,
148 release.published_at.as_deref().unwrap_or(""),
149 names.join(" ")
150 );
151 }
152 let packages = repo_package_links(state, viewer, repo_id).await?;
153 let package_text: Vec<String> = packages
154 .iter()
155 .map(|link| format!("{} {}", link.name, link.latest))
156 .collect();
157 Ok(format!("{release_text}\n{}", package_text.join("\n")))
158}
159
160/// The repo's live stream. Auth is the repo read check of the page: a viewer who cannot read the
161/// repo gets the same 404 as the page.
162#[route(GET "/{owner}/{repo}/events")]
163async fn repo_events(cx: &Cx) -> Result<Response> {
164 let owner = owner(cx);
165 let name = repo(cx);
166 let query = query_params::<LiveQuery>(cx)?;
167 let branch = query.ref_name.clone().unwrap_or_default();
168 let home = query.home.as_deref() == Some("1");
169 let ctx = load_repo(cx, owner, name).await?;
170 let state = context::<AppState>(cx).clone();
171 let repo_id = ctx.repo.id.clone();
172 let mut topics = vec![
173 Topic::Repo(repo_id.clone()),
174 Topic::RepoIssues(repo_id.clone()),
175 Topic::PullList(repo_id.clone()),
176 ];
177 if !branch.is_empty() {
178 topics.push(Topic::RepoRefs(repo_id.clone()));
179 }
180 if home {
181 topics.push(Topic::RepoReleases(repo_id.clone()));
182 }
183 // The home page lists the newest CI runs, which the CI hub signals.
184 let extra = if home {
185 vec![state.ci_live.subscribe_repo(&repo_id)]
186 } else {
187 Vec::new()
188 };
189 let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone());
190 let path = ctx.path.clone();
191 stream_changes_with(cx, &state.live.clone(), &topics, extra, move || {
192 let state = state.clone();
193 let repo_id = repo_id.clone();
194 let path = path.clone();
195 let branch = branch.clone();
196 let viewer = viewer.clone();
197 async move {
198 let viewer_id = viewer.as_ref().map(|user| user.id.as_str());
199 let mut out = header_fingerprint(&state, &repo_id, viewer_id).await?;
200 if !branch.is_empty() {
201 let refs = refs_fingerprint(path, branch).await?;
202 out = format!("{out}\n{refs}");
203 }
204 if home {
205 let extra = home_fingerprint(&state, &repo_id, viewer.as_ref()).await?;
206 let runs = runs_fingerprint(&state, &repo_id).await?;
207 out = format!("{out}\n{extra}\n{runs}");
208 }
209 Ok(out)
210 }
211 })
212 .await
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 #[tokio::test]
220 async fn opening_an_issue_changes_the_header_state() {
221 let dir = tempfile::tempdir().unwrap();
222 let state = crate::test_support::test_state(dir.path()).await;
223 let user = state
224 .store
225 .create_user("tahinli", None, "x", false)
226 .await
227 .unwrap();
228 let repo = state
229 .store
230 .create_repo(&user.id, "demo", "", Visibility::Public, "main")
231 .await
232 .unwrap();
233 let before = header_fingerprint(&state, &repo.id, None).await.unwrap();
234
235 state
236 .store
237 .create_issue(&repo.id, &user.id, "Broken build", "")
238 .await
239 .unwrap();
240
241 let after = header_fingerprint(&state, &repo.id, None).await.unwrap();
242 assert_ne!(before, after);
243 }
244}