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.

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