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.

293 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::{self, Held};
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 /// A slot's first work item (`items::select`).
82 pub(crate) fn held(&self, slot: Slot) -> Result<Option<Held>> {
83 match self.results.get(slot as usize) {
84 Some(result) => Ok(items::held_rows(result)?.into_iter().next()),
85 None => Ok(None),
86 }
87 }
88}
89
90#[derive(serde::Deserialize)]
91struct IdRow {
92 id: String,
93 head_commit: Option<String>,
94}
95
96thread_local! {
97 /// Repository ids by path, as the repos service last answered: a guess
98 /// that lets a page's batch start before the answer comes. Never
99 /// trusted: nothing read with a guess is used unless the repos service
100 /// then says the viewer may see that very repository.
101 static REPO_IDS: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
102}
103
104/// Guesses kept at most; the map is emptied past this.
105const MAX_GUESSES: usize = 1024;
106
107fn path_key(path: &RepoPath) -> String {
108 format!("{}/{}", path.namespace.to_lowercase(), path.name.to_lowercase())
109}
110
111fn guess(path: &RepoPath) -> Option<String> {
112 REPO_IDS.with(|ids| ids.borrow().get(&path_key(path)).cloned())
113}
114
115fn learn(path: &RepoPath, id: Option<&str>) {
116 REPO_IDS.with(|ids| {
117 let mut ids = ids.borrow_mut();
118 match id {
119 Some(id) => {
120 if ids.len() >= MAX_GUESSES {
121 ids.clear();
122 }
123 ids.insert(path_key(path), id.to_owned());
124 }
125 None => {
126 ids.remove(&path_key(path));
127 }
128 }
129 });
130}
131
132impl Work {
133 /// The repository at `path` if `viewer` may see it, and what `load`
134 /// reads for it. When this isolate has seen the repository before,
135 /// `load` starts with its id at once, beside the access check, instead
136 /// of after it: one round trip instead of two. What it read is
137 /// discarded unless the check passes for that same repository.
138 pub(crate) async fn repo_then<T, F, Fut>(&self, path: &RepoPath, viewer: &Viewer, load: F) -> Result<Outcome<(Repo, T)>>
139 where
140 F: Fn(String) -> Fut,
141 Fut: Future<Output = Result<T>>,
142 {
143 let guessed = guess(path);
144 let (found, early) = match &guessed {
145 Some(id) => {
146 let (found, early) = futures_util::future::join(self.repo(path, viewer), load(id.clone())).await;
147 (found?, Some(early))
148 }
149 None => (self.repo(path, viewer).await?, None),
150 };
151 let repo = match found {
152 Outcome::Ok(repo) => repo,
153 Outcome::Fail(failure) => {
154 learn(path, None);
155 return Ok(Outcome::Fail(failure));
156 }
157 };
158 if let (Some(id), Some(Ok(value))) = (&guessed, early)
159 && *id == repo.id
160 {
161 return Ok(Outcome::Ok((repo, value)));
162 }
163 learn(path, Some(&repo.id));
164 let value = load(repo.id.clone()).await?;
165 Ok(Outcome::Ok((repo, value)))
166 }
167
168 fn statement(&self, sql: &str, binds: &[JsValue]) -> Result<D1PreparedStatement> {
169 self.db.prepare(sql).bind(binds)
170 }
171
172 /// Everything a pull request's page and its lifecycle read, in one
173 /// batch. `None` when there is no such pull request.
174 pub(crate) async fn prefetch_pull(&self, repo_id: String, namespace: String, number: u32) -> Result<Option<Prefetched>> {
175 let key = || -> [JsValue; 2] { [repo_id.as_str().into(), number.into()] };
176 let with = |extra: JsValue| -> [JsValue; 3] { [repo_id.as_str().into(), number.into(), extra] };
177 let repo_only = || -> [JsValue; 1] { [repo_id.as_str().into()] };
178 let statements = vec![
179 // Slot::Pull: the row, with everything the lifecycle tracks on it.
180 self.statement(&format!("SELECT {PULL_COLUMNS} FROM pulls WHERE repo_id = ?1 AND number = ?2"), &key())?,
181 // Slot::Item
182 self.statement(
183 &items::select("id = (SELECT item_id FROM pulls WHERE repo_id = ?1 AND number = ?2)"),
184 &key(),
185 )?,
186 // Slot::Comments (lib.rs `comments`)
187 self.statement("SELECT * FROM comments WHERE repo_id = ?1 AND number = ?2 ORDER BY id LIMIT 500", &key())?,
188 // Slot::Verdicts: every verdict, oldest first, for the approval
189 // rule, a person's request for changes and a person's approval.
190 self.statement(
191 "SELECT author_id, author_name, verdict, created_at FROM comments
192 WHERE repo_id = ?1 AND number = ?2 AND verdict IS NOT NULL ORDER BY id",
193 &key(),
194 )?,
195 // Slot::Runs: the latest and the ten before it (checks.rs).
196 self.statement(
197 &format!("SELECT * FROM check_runs WHERE pull_id = {PULL_ID} ORDER BY id DESC LIMIT ?3"),
198 &with(RECENT_RUNS.into()),
199 )?,
200 // Slot::Statuses: on its head (statuses.rs `statuses`).
201 self.statement(
202 "SELECT context, state, description, target_url, updated_at, source, check_run_id FROM commit_statuses
203 WHERE repo_id = ?1 AND sha = (SELECT head_commit FROM pulls WHERE repo_id = ?1 AND number = ?2)
204 ORDER BY context",
205 &key(),
206 )?,
207 // Slot::Settings (settings.rs `settings`)
208 self.statement("SELECT * FROM repo_settings WHERE repo_id = ?1", &repo_only())?,
209 // Slot::Others (reviews.rs `overlaps`)
210 self.statement(
211 concat!(
212 "SELECT number, title, ",
213 items::sql::item_number!("pulls.item_id"),
214 " AS item_number,
215 files FROM pulls
216 WHERE repo_id = ?1 AND number != ?2 AND status IN ('draft', 'open')
217 ORDER BY number LIMIT 200"
218 ),
219 &key(),
220 )?,
221 // Slot::Queued (queue.rs `queued_entry`)
222 self.statement(
223 &format!(
224 "SELECT * FROM queue_entries
225 WHERE pull_id = {PULL_ID} AND state IN ('waiting', 'testing', 'passed') LIMIT 1"
226 ),
227 &key(),
228 )?,
229 // Slot::Rulesets and Slot::Adopted (rulesets.rs `rulesets_for`)
230 self.statement(crate::rulesets::prefetch_sql().0, &[repo_id.as_str().into(), namespace.to_lowercase().into()])?,
231 self.statement(crate::rulesets::prefetch_sql().1, &repo_only())?,
232 // Slot::Reactions (reactions.rs `THREAD_SQL`)
233 self.statement(crate::reactions::THREAD_SQL, &key())?,
234 ];
235 let count = statements.len() as u32;
236 let results = self.timing.db(count, self.db.batch(statements)).await?;
237 let Some(row) = results
238 .first()
239 .map(|result| result.results::<IdRow>())
240 .transpose()?
241 .and_then(|rows| rows.into_iter().next())
242 else {
243 return Ok(None);
244 };
245 Ok(Some(Prefetched {
246 pull_id: row.id,
247 repo_id,
248 namespace: namespace.to_lowercase(),
249 head: row.head_commit,
250 results,
251 }))
252 }
253
254 /// The rows read for pull request `pull_id` in this request, if any.
255 pub(crate) fn prefetched_pull(&self, pull_id: &str) -> Option<Rc<Prefetched>> {
256 self.prefetched
257 .borrow()
258 .as_ref()
259 .filter(|found| found.pull_id == pull_id)
260 .cloned()
261 }
262
263 /// The rows read in this request for a pull request of `repo_id`.
264 pub(crate) fn prefetched_repo(&self, repo_id: &str) -> Option<Rc<Prefetched>> {
265 self.prefetched
266 .borrow()
267 .as_ref()
268 .filter(|found| found.repo_id == repo_id)
269 .cloned()
270 }
271
272 /// Keeps `found` for the rest of this request.
273 pub(crate) fn keep_prefetched(&self, found: Option<Prefetched>) {
274 *self.prefetched.borrow_mut() = found.map(Rc::new);
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 fn at(namespace: &str, name: &str) -> RepoPath {
283 RepoPath { namespace: namespace.to_owned(), name: name.to_owned() }
284 }
285
286 #[test]
287 fn guesses_ignore_case_and_are_forgotten_on_refusal() {
288 learn(&at("Flagon-IO", "G1T"), Some("repo_1"));
289 assert_eq!(guess(&at("flagon-io", "g1t")).as_deref(), Some("repo_1"));
290 learn(&at("flagon-io", "g1t"), None);
291 assert_eq!(guess(&at("flagon-io", "g1t")), None);
292 }
293}