forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

pull_live.rs197 lines, 7.6 KiBHistoryRawDownload
1//! Live pull requests. The pull list (`/{o}/{r}/pulls`) follows [`Topic::PullList`]; a pull page
2//! and its tabs (conversation, commits, files) follow [`Topic::Pull`]. The pages render `data-live`
3//! with the URL of their stream, and a `changed` event re-renders them in place (see `nav.js`).
4//!
5//! Every write reaches a topic through one of these paths:
6//! - A POST under `/{o}/{r}/pulls/...` (comment, review, label, merge, draft, branch, ...): the
7//! [`PullWriteLayer`] bumps after the handler ran, so no route calls a bump itself.
8//! - A commit status (CI or the status API): [`crate::live::bump_head`], from `automerge::on_status`.
9//! - A push, a mergeability refresh or an auto-merge: [`crate::live::bump_repo_pulls`], from the
10//! call site.
11//!
12//! The bump helpers in [`crate::live`] are the one place each topic is bumped from. A new write
13//! path calls one of them; it does not bump a topic directly.
14//!
15//! What a stream compares is a fingerprint of what the page shows ([`pull_fingerprint`],
16//! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap.
17
18use forge_core::PullRequest;
19use forge_core::reactions::ReactionTarget;
20use forge_core::store::Store;
21use topcoat::Result;
22use topcoat::context::{Cx, context};
23use topcoat::router::response::Response;
24use topcoat::router::{path_param, route};
25
26use crate::live::{Topic, stream_changes};
27use crate::pages::issue_parts::parse_number;
28use crate::pages::repo_ctx::load_repo;
29use crate::state::AppState;
30
31path_param!(owner);
32path_param!(repo);
33path_param!(number);
34
35// Fingerprints. Each reads what the page shows; any change to it changes the string.
36
37/// What one pull request page shows, as one string. `viewer` is the reader: a pending review is
38/// the viewer's own and shows only to them.
39pub async fn pull_fingerprint(
40 store: &Store,
41 repo_id: &str,
42 pr: &PullRequest,
43 viewer: Option<&str>,
44) -> Result<String> {
45 let id = pr.issue.id.as_str();
46 let labels = store.issue_labels(id).await?;
47 let assignees = store.issue_assignees(id).await?;
48 let reviewers = store.requested_reviewers(id).await?;
49 let comments = store.list_comments(id).await?;
50 let reviews = store.list_reviews(id).await?;
51 let threads = store.review_threads(id, viewer).await?;
52 let statuses = store.statuses_for(repo_id, &pr.head_oid).await?;
53 // The reactions of the body, then of each comment in the comments' order. A map's own order is
54 // not stable, so each target is looked up by its id.
55 let comment_ids: Vec<String> = comments.iter().map(|c| c.id.clone()).collect();
56 let body_reactions = store
57 .reactions_for(ReactionTarget::Issue, &[id.to_owned()], viewer)
58 .await?;
59 let comment_reactions = store
60 .reactions_for(ReactionTarget::Comment, &comment_ids, viewer)
61 .await?;
62 let mut reaction_digest = vec![format!("{:?}", body_reactions.get(id))];
63 reaction_digest.extend(
64 comment_ids
65 .iter()
66 .map(|cid| format!("{:?}", comment_reactions.get(cid))),
67 );
68 let events = store.list_events(id).await?;
69 // The merge gate reads the repo's protection rules, so a rule change changes the page.
70 let rules = store.list_branch_rules(repo_id).await?;
71 let subscription = match viewer {
72 Some(viewer) => store.subscription(viewer, id).await?,
73 None => None,
74 };
75
76 let mut lines = vec![
77 format!(
78 "{:?} {:?} {} {} {}",
79 pr.issue.state,
80 pr.issue.state_reason,
81 pr.issue.title,
82 pr.issue.updated_at,
83 pr.issue.comment_count
84 ),
85 format!("body {}", pr.issue.body),
86 format!(
87 "milestone {:?} locked {} {:?}",
88 pr.issue.milestone_id, pr.issue.locked, pr.issue.lock_reason
89 ),
90 format!("reactions {}", reaction_digest.join(" ")),
91 format!(
92 "events {} last {:?}",
93 events.len(),
94 events.last().map(|e| e.id.as_str())
95 ),
96 format!("subscription {subscription:?}"),
97 format!("rules {rules:?}"),
98 format!(
99 "draft {} head {} base {} {:?} {:?} {:?} {:?}",
100 pr.draft,
101 pr.head_oid,
102 pr.base_oid,
103 pr.mergeable,
104 pr.merged_at,
105 pr.merge_commit,
106 pr.conflict_files
107 ),
108 format!(
109 "branch {:?} {} auto {:?}",
110 pr.head_repo_id, pr.head_branch, pr.auto_merge
111 ),
112 format!("labels {labels:?}"),
113 format!("assignees {assignees:?}"),
114 format!("reviewers {reviewers:?}"),
115 ];
116 lines.extend(comments.iter().map(|c| format!("comment {c:?}")));
117 lines.extend(reviews.iter().map(|r| format!("review {r:?}")));
118 lines.extend(threads.iter().map(|t| format!("thread {t:?}")));
119 lines.extend(statuses.iter().map(|s| format!("status {s:?}")));
120 Ok(lines.join("\n"))
121}
122
123/// What the pull request list shows: the fingerprint of every pull of the repo, in number order.
124pub async fn list_fingerprint(
125 store: &Store,
126 repo_id: &str,
127 viewer: Option<&str>,
128) -> Result<String> {
129 let mut parts = Vec::new();
130 for (_, number) in store.pull_refs(repo_id).await? {
131 let Some(pr) = store.pull_by_number(repo_id, number).await? else {
132 continue;
133 };
134 parts.push(pull_fingerprint(store, repo_id, &pr, viewer).await?);
135 }
136 Ok(parts.join("\n#\n"))
137}
138
139/// The fingerprint of one pull request by number. `gone` once it no longer exists.
140async fn pull_read(
141 store: &Store,
142 repo_id: &str,
143 number: i64,
144 viewer: Option<&str>,
145) -> Result<String> {
146 match store.pull_by_number(repo_id, number).await? {
147 Some(pr) => pull_fingerprint(store, repo_id, &pr, viewer).await,
148 None => Ok("gone".to_owned()),
149 }
150}
151
152// Streams
153
154/// The stream URL of one pull request, for its page and its edit history.
155pub fn pull_live_url(owner: &str, repo: &str, number: i64) -> String {
156 format!("/{owner}/{repo}/pulls/{number}/events")
157}
158
159/// The pull list's change stream. Auth is the repo read check of the list page.
160#[route(GET "/{owner}/{repo}/pulls/events")]
161async fn pulls_events(cx: &Cx) -> Result<Response> {
162 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
163 let state = context::<AppState>(cx);
164 let topic = Topic::PullList(ctx.repo.id.clone());
165 let store = state.store.clone();
166 let repo_id = ctx.repo.id.clone();
167 let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone());
168 stream_changes(cx, &state.live, &[topic], move || {
169 let store = store.clone();
170 let repo_id = repo_id.clone();
171 let viewer = viewer.clone();
172 async move { list_fingerprint(&store, &repo_id, viewer.as_deref()).await }
173 })
174 .await
175}
176
177/// One pull request's change stream. Auth is the page's: the repo read check, then the pull.
178#[route(GET "/{owner}/{repo}/pulls/{number}/events")]
179async fn pull_events(cx: &Cx) -> Result<Response> {
180 let number = parse_number(number(cx))?;
181 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
182 let state = context::<AppState>(cx);
183 let Some(pr) = state.store.pull_by_number(&ctx.repo.id, number).await? else {
184 return Err(topcoat::router::error::not_found().into());
185 };
186 let topic = Topic::Pull(pr.issue.id.clone());
187 let store = state.store.clone();
188 let repo_id = ctx.repo.id.clone();
189 let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone());
190 stream_changes(cx, &state.live, &[topic], move || {
191 let store = store.clone();
192 let repo_id = repo_id.clone();
193 let viewer = viewer.clone();
194 async move { pull_read(&store, &repo_id, number, viewer.as_deref()).await }
195 })
196 .await
197}