forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB3d53dfdTahinli1 month ago208 commits

code_live.rs117 lines, 4.5 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 code view that follows `branch`, whether or not the branch exists yet.
39pub fn branch_live_url(owner: &str, repo: &str, branch: &str) -> String {
40 format!("/{owner}/{repo}/events?ref_name={}", percent_encode(branch))
41}
42
43/// The stream URL of a repo page. A code view of a branch adds the branch to it.
44pub fn live_url(owner: &str, repo: &str, refs: &[RefInfo], ref_name: &str) -> String {
45 if follows_branch(refs, ref_name) {
46 branch_live_url(owner, repo, ref_name)
47 } else {
48 format!("/{owner}/{repo}/events")
49 }
50}
51
52/// The state the code view shows: every branch and tag name, and the commit `branch` points at.
53/// A move of another branch leaves it unchanged.
54async fn refs_fingerprint(path: PathBuf, branch: String) -> Result<String> {
55 let refs = load_refs(path).await?;
56 let mut names: Vec<String> = refs
57 .iter()
58 .map(|r| format!("{} {}", r.kind == RefKind::Branch, r.name))
59 .collect();
60 names.sort();
61 let at = refs
62 .iter()
63 .find(|r| r.kind == RefKind::Branch && r.name == branch)
64 .map_or("", |r| r.target.as_str());
65 Ok(format!("{}\n{at}", names.join("\n")))
66}
67
68/// The state the repo header shows. A repo that is gone reads as empty, which ends nothing: the
69/// stream then sends `changed` once and the page's own re-read shows the 404.
70async fn header_fingerprint(state: &AppState, repo_id: &str) -> Result<String> {
71 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
72 return Ok(String::new());
73 };
74 let stars = state.store.star_count(repo_id).await?;
75 let watchers = state.store.watchers(repo_id).await?.len();
76 let forks = fork_count(state, repo_id).await?;
77 let public = repo.visibility == Visibility::Public;
78 Ok(format!(
79 "{}\n{}\n{public}\n{}\n{stars} {watchers} {forks}",
80 repo.owner_name, repo.name, repo.description
81 ))
82}
83
84/// The repo's live stream. Auth is the repo read check of the page: a viewer who cannot read the
85/// repo gets the same 404 as the page.
86#[route(GET "/{owner}/{repo}/events")]
87async fn repo_events(cx: &Cx) -> Result<Response> {
88 let owner = path_param::<Owner>(cx);
89 let name = path_param::<Repo>(cx);
90 let branch = query_params::<LiveQuery>(cx)?
91 .ref_name
92 .clone()
93 .unwrap_or_default();
94 let ctx = load_repo(cx, owner, name).await?;
95 let state = app_context::<AppState>(cx).clone();
96 let mut topics = vec![Topic::Repo(ctx.repo.id.clone())];
97 if !branch.is_empty() {
98 topics.push(Topic::RepoRefs(ctx.repo.id.clone()));
99 }
100 let path = ctx.path.clone();
101 let repo_id = ctx.repo.id.clone();
102 stream_changes(cx, &state.live.clone(), &topics, move || {
103 let state = state.clone();
104 let repo_id = repo_id.clone();
105 let path = path.clone();
106 let branch = branch.clone();
107 async move {
108 let header = header_fingerprint(&state, &repo_id).await?;
109 if branch.is_empty() {
110 return Ok(header);
111 }
112 let refs = refs_fingerprint(path, branch).await?;
113 Ok(format!("{header}\n{refs}"))
114 }
115 })
116 .await
117}