diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs
index 18de8e72..5b4cca5d 100644
--- a/app/src/forge/github.rs
+++ b/app/src/forge/github.rs
@@ -77,48 +77,95 @@ pub struct Reach {
pub listings: Vec
,
}
+/// How many of a listing's GitHub calls are in flight at once: a sign-in's wait is its slowest chain of calls, not their
+/// sum, and four stays well inside GitHub's secondary rate limit on concurrent requests.
+const CONCURRENT_CALLS: usize = 4;
+
/// List what the person's token reaches ([`Reach`]): at most one page of installations and
-/// [`SIGN_IN_REPOSITORY_PAGES`] pages of repositories.
+/// [`SIGN_IN_REPOSITORY_PAGES`] pages of repositories. The first page of each installation's repositories is read at
+/// once (each says its total), then the pages left are shared out in installation order and read at once too, so the
+/// wait is about three calls long however many it makes.
///
/// # Errors
/// When GitHub can't be reached or refuses.
pub async fn reachable(token: &str) -> laravel::Result {
- let mut listings = Vec::new();
- let mut found = Vec::new();
- let mut out = Vec::new();
- let mut reachable = Vec::new();
- let listed = pages(token, "/user/installations", "installations", 1).await?;
- if listed.more {
+ use futures_util::{StreamExt as _, TryStreamExt as _};
+
+ let (installations, _) = page(token, "/user/installations", "installations", 1).await?;
+ if installations.len() >= 100 {
tracing::warn!(shown = SIGN_IN_INSTALLATIONS, "a sign-in can reach more installations than it lists");
}
- let mut pages_left = SIGN_IN_REPOSITORY_PAGES;
- let mut skipped = 0;
- for item in listed.items {
+ let mut found = Vec::new();
+ let mut ids = Vec::new();
+ for item in &installations {
let Some(installation) = item["id"].as_i64() else { continue };
if let Some(account) = installation_account(installation.to_string(), &item["account"]) {
found.push(account);
}
- if pages_left == 0 {
- skipped += 1;
- listings.push(Listing { installation_id: installation.to_string(), listed: 0, total: None });
+ ids.push(installation);
+ }
+ let paths: Vec = ids.iter().map(|id| format!("/user/installations/{id}/repositories")).collect();
+
+ // Each installation's first page, up to the cap: what's past it gets none
+ let firsts = usize::try_from(SIGN_IN_REPOSITORY_PAGES).unwrap_or(usize::MAX).min(ids.len());
+ // Collected first: a stream over a closure isn't `Send` enough for a job's future
+ let calls: Vec<_> = paths[..firsts]
+ .iter()
+ .cloned()
+ .map(|path| async move { page(token, &path, "repositories", 1).await })
+ .collect();
+ let first_pages: Vec<(Vec, Option)> =
+ futures_util::stream::iter(calls).buffered(CONCURRENT_CALLS).try_collect().await?;
+
+ // The pages left, shared out in installation order: as many as each one's total needs, up to its own cap
+ let mut left = SIGN_IN_REPOSITORY_PAGES - u32::try_from(firsts).unwrap_or(SIGN_IN_REPOSITORY_PAGES);
+ let mut more_pages: Vec<(usize, u32)> = Vec::new();
+ for (i, (items, total)) in first_pages.iter().enumerate() {
+ if items.len() < 100 {
continue;
}
- let path = format!("/user/installations/{installation}/repositories");
- let repos = pages(token, &path, "repositories", pages_left.min(SIGN_IN_PAGES_PER_INSTALLATION)).await?;
- pages_left -= repos.read;
+ let needed =
+ total.map_or(SIGN_IN_PAGES_PER_INSTALLATION, |t| u32::try_from((t + 99) / 100).unwrap_or(u32::MAX));
+ let more = needed.min(SIGN_IN_PAGES_PER_INSTALLATION).saturating_sub(1).min(left);
+ left -= more;
+ more_pages.extend((2..2 + more).map(|n| (i, n)));
+ }
+ let calls: Vec<_> = more_pages
+ .iter()
+ .map(|&(i, n)| {
+ let path = paths[i].clone();
+ async move { page(token, &path, "repositories", n).await }
+ })
+ .collect();
+ let rest: Vec<(Vec, Option)> =
+ futures_util::stream::iter(calls).buffered(CONCURRENT_CALLS).try_collect().await?;
+ let mut by_installation: Vec> = first_pages.iter().map(|(items, _)| items.clone()).collect();
+ for (&(i, _), (items, _)) in more_pages.iter().zip(rest) {
+ by_installation[i].extend(items);
+ }
+
+ let mut listings = Vec::new();
+ let mut out = Vec::new();
+ let mut reachable = Vec::new();
+ for (i, installation) in ids.iter().enumerate() {
+ let Some(repos) = by_installation.get_mut(i).map(std::mem::take) else {
+ listings.push(Listing { installation_id: installation.to_string(), listed: 0, total: None });
+ continue;
+ };
+ let total = first_pages[i].1;
listings.push(Listing {
installation_id: installation.to_string(),
- listed: i32::try_from(repos.items.len()).unwrap_or(i32::MAX),
- total: repos.total.map(|t| i32::try_from(t).unwrap_or(i32::MAX)),
+ listed: i32::try_from(repos.len()).unwrap_or(i32::MAX),
+ total: total.map(|t| i32::try_from(t).unwrap_or(i32::MAX)),
});
- if repos.more {
+ if total.is_some_and(|t| i64::try_from(repos.len()).unwrap_or(i64::MAX) < t) {
tracing::warn!(
installation,
- listed = repos.items.len(),
+ listed = repos.len(),
"a sign-in listed only some of an installation's repositories"
);
}
- for repo in repos.items {
+ for repo in repos {
let (Some(repository), Some(permission)) =
(repo["full_name"].as_str().and_then(Repository::parse), permission_from_flags(&repo["permissions"]))
else {
@@ -137,9 +184,9 @@ pub async fn reachable(token: &str) -> laravel::Result {
out.push((repository, permission));
}
}
- if skipped > 0 {
+ if ids.len() > firsts {
tracing::warn!(
- installations = skipped,
+ installations = ids.len() - firsts,
"a sign-in listed no repositories of some installations: past its page cap"
);
}
@@ -157,46 +204,22 @@ pub fn installation_account(id: String, account: &Value) -> Option
})
}
-/// Items of a paged list, and whether GitHub has more past the pages read.
-struct Paged {
- items: Vec,
- /// GitHub's `total_count` on the first page, when it says.
- total: Option,
- /// Pages read (GitHub calls made).
- read: u32,
- more: bool,
-}
-
-/// The items of a paged list (`key` in each page's object), 100 a page, up to `max_pages` pages.
-async fn pages(token: &str, path: &str, key: &str, max_pages: u32) -> laravel::Result {
- let mut paged = Paged { items: Vec::new(), total: None, read: 0, more: false };
- for page in 1..=max_pages {
- let response = client::get(format!("{}{path}", api()))
- .token(token)
- .accept_json()
- .query([("per_page", 100), ("page", page)])
- .await?;
- paged.read += 1;
- if response.status() == 401 {
- // The person's token: revoked, or expired before it was forgotten
- return Err(laravel::abort_with(401, format!("GitHub {path}: HTTP 401, the token isn't valid")));
- }
- if !response.successful() {
- return Err(laravel::Error::msg(format!("GitHub {path}: HTTP {}", response.status())));
- }
- let body: Value = response.json()?;
- if page == 1 {
- paged.total = body["total_count"].as_i64();
- }
- let list = body[key].as_array().cloned().unwrap_or_default();
- let full = list.len() >= 100;
- paged.items.extend(list);
- if !full {
- return Ok(paged);
- }
- paged.more = page == max_pages;
+/// Page `n` of a paged list (`key` in its object, 100 a page), and GitHub's `total_count` when it says.
+async fn page(token: &str, path: &str, key: &str, n: u32) -> laravel::Result<(Vec, Option)> {
+ let response = client::get(format!("{}{path}", api()))
+ .token(token)
+ .accept_json()
+ .query([("per_page", 100), ("page", n)])
+ .await?;
+ if response.status() == 401 {
+ // The person's token: revoked, or expired before it was forgotten
+ return Err(laravel::abort_with(401, format!("GitHub {path}: HTTP 401, the token isn't valid")));
+ }
+ if !response.successful() {
+ return Err(laravel::Error::msg(format!("GitHub {path}: HTTP {}", response.status())));
}
- Ok(paged)
+ let body: Value = response.json()?;
+ Ok((body[key].as_array().cloned().unwrap_or_default(), body["total_count"].as_i64()))
}
/// The highest permission GitHub's flags give (`{"admin": false, "push": true, …}`).
diff --git a/app/tests/github_calls.rs b/app/tests/github_calls.rs
index 2f8c2364..99715ec0 100644
--- a/app/tests/github_calls.rs
+++ b/app/tests/github_calls.rs
@@ -77,14 +77,14 @@ async fn a_handler_that_loops_over_a_github_list_fails(app: Application) -> lara
}
/// A page of `count` repositories numbered from `first`, for installation `owner`.
-fn page_of(owner: &str, first: usize, count: usize) -> serde_json::Value {
+fn page_of(owner: &str, first: usize, count: usize, total: usize) -> serde_json::Value {
let repositories: Vec = (first..first + count)
.map(|n| {
json!({ "id": 10_000_000 + n, "full_name": format!("{owner}/repo-{n}"), "private": true,
"permissions": { "admin": true, "maintain": true, "push": true, "pull": true } })
})
.collect();
- json!({ "repositories": repositories })
+ json!({ "total_count": total, "repositories": repositories })
}
/// The `page` a request asked for.
@@ -108,7 +108,7 @@ fn four_organizations(delay: std::time::Duration) -> client::HttpFake {
std::thread::sleep(delay);
let page = page_asked(r.url());
let first = (page - 1) * 100;
- page_of(&owner, first, size.saturating_sub(first).min(100))
+ page_of(&owner, first, size.saturating_sub(first).min(100), size)
},
);
}
@@ -189,9 +189,13 @@ async fn the_listing_after_a_sign_in_reaching_thousands_of_repositories_stays_wi
db::query!("SELECT github_sync_error FROM users WHERE github_sync_error IS NOT NULL").scalar().await?;
assert_eq!(error, None, "the listing failed");
let per = i64::from(SIGN_IN_PAGES_PER_INSTALLATION) * 100;
- // 3 pages for acme, 10 for huge, the 7 left for huger, none for late
- let left = (i64::from(SIGN_IN_REPOSITORY_PAGES) - 3 - i64::from(SIGN_IN_PAGES_PER_INSTALLATION)) * 100;
- assert_eq!(listed, vec![("1".into(), 250), ("2".into(), per), ("3".into(), left)], "{listed:?}");
+ // A first page each, then the pages left in order: 2 more for acme, 9 for huge, the rest for huger, none for late
+ let left = (i64::from(SIGN_IN_REPOSITORY_PAGES) - 4 - 2 - (i64::from(SIGN_IN_PAGES_PER_INSTALLATION) - 1)) * 100;
+ assert_eq!(
+ listed,
+ vec![("1".into(), 250), ("2".into(), per), ("3".into(), 100 + left), ("4".into(), 100)],
+ "{listed:?}"
+ );
let recorded: Option = db::query!("SELECT COUNT(*) FROM user_installations").scalar().await?;
assert_eq!(recorded, Some(4), "every installation recorded, repositories listed or not");
assert_eq!(sign_in_sync::state(ada_id().await?).await?, State::Done);
@@ -251,7 +255,7 @@ async fn an_installation_delivery_with_hundreds_of_repositories_makes_one_call(
.await?;
}
let github = client::fake().with("api.github.com/app/installations/7", json!({ "id": 7 }));
- let repositories: Vec = page_of("acme", 0, 300)["repositories"].as_array().unwrap().clone();
+ let repositories: Vec = page_of("acme", 0, 300, 300)["repositories"].as_array().unwrap().clone();
let body = json!({ "action": "created", "installation": { "id": 7, "account": { "id": 5005, "login": "acme",
"type": "Organization" } }, "repositories": repositories })
.to_string();
diff --git a/docs/design.md b/docs/design.md
index fd6665ea..f21abd3a 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -502,7 +502,8 @@ Every request's GitHub calls are counted (`forge::calls`): a fixed budget per ro
for linking a repository), logged per request, and under
`APP_ENV=testing` a request over budget answers 500, so a handler that loops over a GitHub list fails CI; queued jobs
count their own and stop at page caps (a sign-in's listing reads at most 20 pages of repositories, 10 per
-installation). The picker answers each installation's `listed` and `total`; for an installation
+installation: the first page of each installation, then the pages their totals need in installation order, four calls
+at a time, so the person waits about three calls, not twenty; 4 Dec 2026, five calls one after another took 6.5 s). The picker answers each installation's `listed` and `total`; for an installation
the sign-in didn't list completely, its search asks GitHub once as the person (`search/repositories` scoped to the
account, with the GitHub token kept encrypted from their sign-in, which reaches only what both they and the App can; 30
searches a minute per person) and records what it finds in `user_repositories`. Repository picks go up to 500 at once,