forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.08.8 MiBb00f3f4Tahinli1 month ago147 commits

code_live.rs115 lines, 4.3 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, or the repo's
4//! name, description or visibility. On a code view of a branch it also sends `changed` when the
5//! branch moves, or when a branch or tag is created or deleted (the ref selector and the branch
6//! list depend on that). Moves of other refs send nothing. Commits and tags are not followed: they
7//! do not move.
8
9use std::path::PathBuf;
10
11use forge_core::Visibility;
12use forge_git::browse::{RefInfo, RefKind};
13use topcoat::Result;
14use topcoat::context::{Cx, app_context};
15use topcoat::router::response::Response;
16use topcoat::router::{path_param, query_params, route};
17
18use crate::auth::percent_encode;
19use crate::live::{Topic, stream_changes};
20use crate::pages::refs::load_refs;
21use crate::pages::repo_ctx::{fork_count, load_repo};
22use crate::state::AppState;
23
24path_param!(owner);
25path_param!(repo);
26
27#[query_params(error = bad_request)]
28struct LiveQuery {
29 ref_name: Option<String>,
30}
31
32/// Whether a code view of `ref_name` follows the branch: the ref is a branch of the repo.
33pub fn follows_branch(refs: &[RefInfo], ref_name: &str) -> bool {
34 refs.iter()
35 .any(|r| r.kind == RefKind::Branch && r.name == ref_name)
36}
37
38/// The stream URL of a repo page. A code view of a branch adds the branch to it.
39pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String {
40 if follows_branch(refs, ref_name) {
41 format!(
42 "/{owner}/{repo}/events?ref_name={}",
43 percent_encode(ref_name)
44 )
45 } else {
46 format!("/{owner}/{repo}/events")
47 }
48}
49
50/// The state the code view shows: every branch and tag name, and the commit `branch` points at.
51/// A move of another branch leaves it unchanged.
52async fn refs_fingerprint(path: PathBuf, branch: String) -> Result<String> {
53 let refs = load_refs(path).await?;
54 let mut names: Vec<String> = refs
55 .iter()
56 .map(|r| format!("{} {}", r.kind == RefKind::Branch, r.name))
57 .collect();
58 names.sort();
59 let at = refs
60 .iter()
61 .find(|r| r.kind == RefKind::Branch && r.name == branch)
62 .map_or("", |r| r.target.as_str());
63 Ok(format!("{}\n{at}", names.join("\n")))
64}
65
66/// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the
67/// stream then sends `changed` once and the page's own re-read shows the 404.
68async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result<String> {
69 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
70 return Ok(String::new());
71 };
72 let stars = state.store.star_count(repo_id).await?;
73 let watchers = state.store.watchers(repo_id).await?.len();
74 let forks = fork_count(state, repo_id).await?;
75 let public = repo.visibility == Visibility::Public;
76 Ok(format!(
77 "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks}",
78 repo.owner_name, repo.name, repo.description
79 ))
80}
81
82/// The repo's live stream. Auth is the repo read check of the page: a viewer who cannot read the
83/// repo gets the same 404 as the page.
84#[route(GET "/{owner}/{repo}/events")]
85async fn repo_events(cx: &Cx) -> Result<Response> {
86 let owner = path_param::<Owner>(cx);
87 let name = path_param::<Repo>(cx);
88 let branch = query_params::<LiveQuery>(cx)?
89 .ref_name
90 .clone()
91 .unwrap_or_default();
92 let ctx = load_repo(cx, owner, name).await?;
93 let state = app_context::<AppState>(cx).clone();
94 let mut topics = vec![Topic::Repo(ctx.repo.id.clone())];
95 if !branch.is_empty() {
96 topics.push(Topic::RepoRefs(ctx.repo.id.clone()));
97 }
98 let path = ctx.path.clone();
99 let repo_id = ctx.repo.id.clone();
100 stream_changes(cx, &state.live.clone(), &topics, move || {
101 let state = state.clone();
102 let repo_id = repo_id.clone();
103 let path = path.clone();
104 let branch = branch.clone();
105 async move {
106 let header = header_fingerprint(&state, &repo_id).await?;
107 if branch.is_empty() {
108 return Ok(header);
109 }
110 let refs = refs_fingerprint(path, branch).await?;
111 Ok(format!("{header}\n{refs}"))
112 }
113 })
114 .await
115}