Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

284 linesCodeBlameRaw
1//! Reading a page's worth of rows in one round trip.
2//!
3//! A pull request's page used to cost about twenty queries one after
4//! another: the repository, the pull request, its work item, then where it
5//! stands (its progress, settings, statuses, verdicts and queue entry),
6//! its comments and checks. Each is a round trip to the database, and from most places a
7//! round trip is 20 to 40 ms. Here they go as one D1 batch, keyed by the
8//! repository's id and the pull request's number, and the batch starts
9//! while the repos service is still deciding whether the viewer may see
10//! the repository ([`Work::repo_then`]).
11//!
12//! The helpers that answer those questions (`settings`, `statuses`,
13//! `approvals_gap` and the rest) look here first, so the
14//! code that decides a pull request's lifecycle is the same code whether
15//! its rows were batched or read one at a time. Only reads are kept; a
16//! helper that writes and reads back (mergeability) reads the database.
17
18use std::cell::RefCell;
19use std::collections::HashMap;
20use std::future::Future;
21use std::rc::Rc;
22
23use g1t_contracts::repos::{Repo, RepoPath};
24use g1t_contracts::{Outcome, Viewer};
25use serde::de::DeserializeOwned;
26use worker::wasm_bindgen::JsValue;
27use worker::{D1PreparedStatement, D1Result, Result};
28
29use crate::Work;
30use crate::items::ITEM_COLUMNS;
31use crate::rows::PULL_COLUMNS;
32
33/// The pull request's id, from the batch's `?1` (repository) and `?2` (number).
34const PULL_ID: &str = "(SELECT id FROM pulls WHERE repo_id = ?1 AND number = ?2)";
35
36/// Each statement of a pull request's batch, in order.
37#[derive(Clone, Copy)]
38pub(crate) enum Slot {
39 Pull,
40 Item,
41 Comments,
42 Verdicts,
43 Runs,
44 Statuses,
45 Settings,
46 Others,
47 Queued,
48 Rulesets,
49 Adopted,
50 Reactions,
51}
52
53/// How many runs `latest_checks` and `earlier_checks` show together.
54pub(crate) const RECENT_RUNS: u32 = 11;
55
56/// One pull request's rows, as read for this request.
57pub(crate) struct Prefetched {
58 pub(crate) pull_id: String,
59 pub(crate) repo_id: String,
60 /// The workspace its rulesets were read for, lowercase.
61 pub(crate) namespace: String,
62 /// Its head commit when read, which its statuses are for.
63 pub(crate) head: Option<String>,
64 results: Vec<D1Result>,
65}
66
67impl Prefetched {
68 /// A slot's rows, as the helper that reads them would have.
69 pub(crate) fn rows<T: DeserializeOwned>(&self, slot: Slot) -> Result<Vec<T>> {
70 match self.results.get(slot as usize) {
71 Some(result) => result.results::<T>(),
72 None => Ok(Vec::new()),
73 }
74 }
75
76 /// A slot's first row.
77 pub(crate) fn first<T: DeserializeOwned>(&self, slot: Slot) -> Result<Option<T>> {
78 Ok(self.rows::<T>(slot)?.into_iter().next())
79 }
80}
81
82#[derive(serde::Deserialize)]
83struct IdRow {
84 id: String,
85 head_commit: Option<String>,
86}
87
88thread_local! {
89 /// Repository ids by path, as the repos service last answered: a guess
90 /// that lets a page's batch start before the answer comes. Never
91 /// trusted: nothing read with a guess is used unless the repos service
92 /// then says the viewer may see that very repository.
93 static REPO_IDS: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
94}
95
96/// Guesses kept at most; the map is emptied past this.
97const MAX_GUESSES: usize = 1024;
98
99fn path_key(path: &RepoPath) -> String {
100 format!("{}/{}", path.namespace.to_lowercase(), path.name.to_lowercase())
101}
102
103fn guess(path: &RepoPath) -> Option<String> {
104 REPO_IDS.with(|ids| ids.borrow().get(&path_key(path)).cloned())
105}
106
107fn learn(path: &RepoPath, id: Option<&str>) {
108 REPO_IDS.with(|ids| {
109 let mut ids = ids.borrow_mut();
110 match id {
111 Some(id) => {
112 if ids.len() >= MAX_GUESSES {
113 ids.clear();
114 }
115 ids.insert(path_key(path), id.to_owned());
116 }
117 None => {
118 ids.remove(&path_key(path));
119 }
120 }
121 });
122}
123
124impl Work {
125 /// The repository at `path` if `viewer` may see it, and what `load`
126 /// reads for it. When this isolate has seen the repository before,
127 /// `load` starts with its id at once, beside the access check, instead
128 /// of after it: one round trip instead of two. What it read is
129 /// discarded unless the check passes for that same repository.
130 pub(crate) async fn repo_then<T, F, Fut>(&self, path: &RepoPath, viewer: &Viewer, load: F) -> Result<Outcome<(Repo, T)>>
131 where
132 F: Fn(String) -> Fut,
133 Fut: Future<Output = Result<T>>,
134 {
135 let guessed = guess(path);
136 let (found, early) = match &guessed {
137 Some(id) => {
138 let (found, early) = futures_util::future::join(self.repo(path, viewer), load(id.clone())).await;
139 (found?, Some(early))
140 }
141 None => (self.repo(path, viewer).await?, None),
142 };
143 let repo = match found {
144 Outcome::Ok(repo) => repo,
145 Outcome::Fail(failure) => {
146 learn(path, None);
147 return Ok(Outcome::Fail(failure));
148 }
149 };
150 if let (Some(id), Some(Ok(value))) = (&guessed, early)
151 && *id == repo.id
152 {
153 return Ok(Outcome::Ok((repo, value)));
154 }
155 learn(path, Some(&repo.id));
156 let value = load(repo.id.clone()).await?;
157 Ok(Outcome::Ok((repo, value)))
158 }
159
160 fn statement(&self, sql: &str, binds: &[JsValue]) -> Result<D1PreparedStatement> {
161 self.db.prepare(sql).bind(binds)
162 }
163
164 /// Everything a pull request's page and its lifecycle read, in one
165 /// batch. `None` when there is no such pull request.
166 pub(crate) async fn prefetch_pull(&self, repo_id: String, namespace: String, number: u32) -> Result<Option<Prefetched>> {
167 let key = || -> [JsValue; 2] { [repo_id.as_str().into(), number.into()] };
168 let with = |extra: JsValue| -> [JsValue; 3] { [repo_id.as_str().into(), number.into(), extra] };
169 let repo_only = || -> [JsValue; 1] { [repo_id.as_str().into()] };
170 let statements = vec![
171 // Slot::Pull: the row, with everything the lifecycle tracks on it.
172 self.statement(&format!("SELECT {PULL_COLUMNS} FROM pulls WHERE repo_id = ?1 AND number = ?2"), &key())?,
173 // Slot::Item
174 self.statement(
175 &format!(
176 "SELECT {ITEM_COLUMNS} FROM work_items
177 WHERE id = (SELECT item_id FROM pulls WHERE repo_id = ?1 AND number = ?2)"
178 ),
179 &key(),
180 )?,
181 // Slot::Comments (lib.rs `comments`)
182 self.statement("SELECT * FROM comments WHERE repo_id = ?1 AND number = ?2 ORDER BY id LIMIT 500", &key())?,
183 // Slot::Verdicts: every verdict, oldest first, for the approval
184 // rule, a person's request for changes and a person's approval.
185 self.statement(
186 "SELECT author_id, author_name, verdict, created_at FROM comments
187 WHERE repo_id = ?1 AND number = ?2 AND verdict IS NOT NULL ORDER BY id",
188 &key(),
189 )?,
190 // Slot::Runs: the latest and the ten before it (checks.rs).
191 self.statement(
192 &format!("SELECT * FROM check_runs WHERE pull_id = {PULL_ID} ORDER BY id DESC LIMIT ?3"),
193 &with(RECENT_RUNS.into()),
194 )?,
195 // Slot::Statuses: on its head (statuses.rs `statuses`).
196 self.statement(
197 "SELECT context, state, description, target_url, updated_at, source, check_run_id FROM commit_statuses
198 WHERE repo_id = ?1 AND sha = (SELECT head_commit FROM pulls WHERE repo_id = ?1 AND number = ?2)
199 ORDER BY context",
200 &key(),
201 )?,
202 // Slot::Settings (settings.rs `settings`)
203 self.statement("SELECT * FROM repo_settings WHERE repo_id = ?1", &repo_only())?,
204 // Slot::Others (reviews.rs `overlaps`)
205 self.statement(
206 "SELECT number, title, (SELECT number FROM work_items WHERE work_items.id = pulls.item_id) AS item_number,
207 files FROM pulls
208 WHERE repo_id = ?1 AND number != ?2 AND status IN ('draft', 'open')
209 ORDER BY number LIMIT 200",
210 &key(),
211 )?,
212 // Slot::Queued (queue.rs `queued_entry`)
213 self.statement(
214 &format!(
215 "SELECT * FROM queue_entries
216 WHERE pull_id = {PULL_ID} AND state IN ('waiting', 'testing', 'passed') LIMIT 1"
217 ),
218 &key(),
219 )?,
220 // Slot::Rulesets and Slot::Adopted (rulesets.rs `rulesets_for`)
221 self.statement(crate::rulesets::prefetch_sql().0, &[repo_id.as_str().into(), namespace.to_lowercase().into()])?,
222 self.statement(crate::rulesets::prefetch_sql().1, &repo_only())?,
223 // Slot::Reactions (reactions.rs `THREAD_SQL`)
224 self.statement(crate::reactions::THREAD_SQL, &key())?,
225 ];
226 let count = statements.len() as u32;
227 let results = self.timing.db(count, self.db.batch(statements)).await?;
228 let Some(row) = results
229 .first()
230 .map(|result| result.results::<IdRow>())
231 .transpose()?
232 .and_then(|rows| rows.into_iter().next())
233 else {
234 return Ok(None);
235 };
236 Ok(Some(Prefetched {
237 pull_id: row.id,
238 repo_id,
239 namespace: namespace.to_lowercase(),
240 head: row.head_commit,
241 results,
242 }))
243 }
244
245 /// The rows read for pull request `pull_id` in this request, if any.
246 pub(crate) fn prefetched_pull(&self, pull_id: &str) -> Option<Rc<Prefetched>> {
247 self.prefetched
248 .borrow()
249 .as_ref()
250 .filter(|found| found.pull_id == pull_id)
251 .cloned()
252 }
253
254 /// The rows read in this request for a pull request of `repo_id`.
255 pub(crate) fn prefetched_repo(&self, repo_id: &str) -> Option<Rc<Prefetched>> {
256 self.prefetched
257 .borrow()
258 .as_ref()
259 .filter(|found| found.repo_id == repo_id)
260 .cloned()
261 }
262
263 /// Keeps `found` for the rest of this request.
264 pub(crate) fn keep_prefetched(&self, found: Option<Prefetched>) {
265 *self.prefetched.borrow_mut() = found.map(Rc::new);
266 }
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272
273 fn at(namespace: &str, name: &str) -> RepoPath {
274 RepoPath { namespace: namespace.to_owned(), name: name.to_owned() }
275 }
276
277 #[test]
278 fn guesses_ignore_case_and_are_forgotten_on_refusal() {
279 learn(&at("Flagon-IO", "G1T"), Some("repo_1"));
280 assert_eq!(guess(&at("flagon-io", "g1t")).as_deref(), Some("repo_1"));
281 learn(&at("flagon-io", "g1t"), None);
282 assert_eq!(guess(&at("flagon-io", "g1t")), None);
283 }
284}