Skip to content

Commit 7c9e713

Browse files
committed
Renames, second round: rate limits defer the sync; renames follow GitHub's current login
Review fixes for #278 (246d357): - collaborators returns None (unseen, so unlinked) only for a 404 or a 403 "Resource not accessible by integration" without retry-after. A rate limit's answer (429, or a 403 with no calls left, retry-after or a rate-limit message) is an error rate_limited() recognises, from get(), collaborators and installation_token alike, so the hourly sync defers with a healthy heartbeat. Any other 403 fails the run and unlinks nobody. - account_renamed: once GitHub confirms the delivery's new login, the installation's login is set to GitHub's whatever VisualCI had, and URLs and picker names move from both the delivery's `from` and the stored login, so acme->beta->gamma delivered after GitHub says gamma, or a lost delivery, ends at gamma. - follow_renames is compare-and-set: reach snapshots each link's URL before asking GitHub, and a URL a webhook changed meanwhile isn't overwritten. - A repository renamed/transferred delivery moves only links through the installation that sent it (a delivery without an installation is ignored). Tests: secondary-limit, primary-limit and 429 answers defer and leave the project linked; a bare 403 errors without unlinking; acme->beta->gamma and a lost delivery end at gamma; the sync doesn't undo a webhook's newer URL; a rename leaves another installation's link to the same repository alone.
1 parent 246d357 commit 7c9e713

6 files changed

Lines changed: 301 additions & 74 deletions

File tree

‎app/src/forge/github_app.rs‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,44 @@ async fn get(token: &str, path: &str) -> laravel::Result<Option<Value>> {
5454
if response.status() == 401 {
5555
token_refused(token).await;
5656
}
57+
if rate_limit_answer(&response) {
58+
return Err(rate_limit_error(&format!("GET {path}"), &response));
59+
}
5760
if !response.successful() {
5861
return Err(err(format!("GET {path}: HTTP {}", response.status())));
5962
}
6063
Ok(Some(response.json()?))
6164
}
6265

66+
/// What [`rate_limited`] looks for in an error made from a rate-limit answer.
67+
const RATE_LIMIT_ANSWER: &str = "GitHub's rate limit answered";
68+
69+
/// Whether GitHub's answer is its rate limit, primary or secondary: a 429, or a 403 with no calls left, a
70+
/// `retry-after`, or a message naming a rate limit. Such an answer says nothing about access.
71+
fn rate_limit_answer(response: &client::Response) -> bool {
72+
response.status() == 429
73+
|| (response.status() == 403
74+
&& (response.header("x-ratelimit-remaining") == Some("0")
75+
|| response.header("retry-after").is_some()
76+
|| response.text().to_ascii_lowercase().contains("rate limit")))
77+
}
78+
79+
/// The error for a rate-limit answer, which [`rate_limited`] recognises so the sync defers instead of failing.
80+
fn rate_limit_error(what: &str, response: &client::Response) -> laravel::Error {
81+
err(format!("{what}: HTTP {}, {RATE_LIMIT_ANSWER}", response.status()))
82+
}
83+
84+
/// Whether a 403 says the installation can't read the resource ("Resource not accessible by integration"), and isn't
85+
/// a rate limit. Any other 403 (no message, or another reason) isn't taken as "can't see it".
86+
fn not_accessible(response: &client::Response) -> bool {
87+
response.status() == 403
88+
&& !rate_limit_answer(response)
89+
&& response
90+
.json::<Value>()
91+
.ok()
92+
.is_some_and(|body| body["message"].as_str() == Some("Resource not accessible by integration"))
93+
}
94+
6395
/// How long before GitHub's expiry a cached installation token stops being used.
6496
const TOKEN_MARGIN_SECONDS: i64 = 300;
6597

@@ -95,6 +127,9 @@ pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel:
95127
.header("accept", "application/vnd.github+json")
96128
.header("user-agent", "visualci")
97129
.await?;
130+
if rate_limit_answer(&response) {
131+
return Err(rate_limit_error("installation token", &response));
132+
}
98133
if !response.successful() {
99134
return Err(err(format!("installation token: HTTP {}", response.status())));
100135
}
@@ -301,10 +336,12 @@ fn numeric(id: Option<&str>) -> Option<&str> {
301336

302337
/// Every collaborator on a repository (at [`repo_api`]) with their permission, keyed by GitHub user ID: direct
303338
/// collaborators, team members and organization members with access, as `affiliation=all` lists them. Public
304-
/// visibility gives nobody a place on it. `None` when GitHub answers 403 or 404: the installation can't read it (a
305-
/// public repository transferred to an account the installation doesn't cover still answers `GET /repositories/{id}`,
306-
/// but not this), so the caller treats the repository as unseen. `Err` when it can't be read completely (a partial list
307-
/// would drop people); also when GitHub's rate limit is down to [`RATE_LIMIT_RESERVE`], or a 403 is the rate limit's.
339+
/// visibility gives nobody a place on it. `None` when GitHub answers 404, or 403 "Resource not accessible by
340+
/// integration": the installation can't read it (a public repository transferred to an account the installation
341+
/// doesn't cover still answers `GET /repositories/{id}`, but not this), so the caller treats the repository as unseen.
342+
/// `Err` when it can't be read completely (a partial list would drop people); also when GitHub's rate limit is down to
343+
/// [`RATE_LIMIT_RESERVE`] or answers instead (a 429, or a primary or secondary limit's 403), which [`rate_limited`]
344+
/// recognises, and on any other 403.
308345
///
309346
/// # Errors
310347
/// Those.
@@ -321,10 +358,14 @@ pub async fn collaborators(token: &str, repo: &str) -> laravel::Result<Option<Ve
321358
token_refused(token).await;
322359
}
323360
let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::<i64>().ok());
324-
// Not readable by this installation; a 403 with no calls left is the rate limit, which stays an error
325-
if response.status() == 404 || (response.status() == 403 && remaining != Some(0)) {
361+
// Not readable by this installation: only a 404, or a 403 that says so. A rate limit (403 or 429, primary or
362+
// secondary) or any other 403 is an error, so the sync defers or fails instead of unlinking anyone
363+
if response.status() == 404 || not_accessible(&response) {
326364
return Ok(None);
327365
}
366+
if rate_limit_answer(&response) {
367+
return Err(rate_limit_error(&format!("GET {repo}/collaborators"), &response));
368+
}
328369
if !response.successful() {
329370
return Err(err(format!("GET {repo}/collaborators: HTTP {}", response.status())));
330371
}
@@ -412,10 +453,12 @@ pub async fn repository_id(token: &str, repo: &str) -> laravel::Result<Option<St
412453
Ok(get(token, &format!("/repos/{repo}")).await?.and_then(|v| v["id"].as_i64().map(|i| i.to_string())))
413454
}
414455

415-
/// Whether an error is GitHub's rate limit running low ([`collaborators`]): the work waits for the next run.
456+
/// Whether an error is GitHub's rate limit running low ([`collaborators`]) or answering instead of the API (a 429, or
457+
/// a primary or secondary limit's 403): the work waits for the next run.
416458
#[must_use]
417459
pub fn rate_limited(e: &laravel::Error) -> bool {
418-
e.to_string().contains("the rate limit is down")
460+
let e = e.to_string();
461+
e.contains("the rate limit is down") || e.contains(RATE_LIMIT_ANSWER)
419462
}
420463

421464
/// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`).

‎app/src/forge/sync.rs‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -112,30 +112,42 @@ async fn backfill_ids(app: &GithubApp) -> laravel::Result<Vec<i64>> {
112112
/// Give links the URL their repository has now, by GitHub's ID ([`Reach::paths`]): a repository renamed or transferred,
113113
/// or an organization renamed (which sends no per-repository `renamed` delivery), whose webhook was missed. Only links
114114
/// through the installation that read it, and only where that installation could list its collaborators, so a project
115-
/// is never pointed at an owner its installation doesn't cover. The repository picker's cached names follow too.
116-
/// Returns how many projects changed.
117-
async fn follow_renames(reach: &Reach) -> laravel::Result<usize> {
118-
if reach.paths.is_empty() {
115+
/// is never pointed at an owner its installation doesn't cover. A URL is replaced only if it's still the one read before
116+
/// GitHub was asked ([`Reach::links`]): a webhook that moved it meanwhile knows a newer name than this run read. The
117+
/// repository picker's cached names follow too. Returns how many projects changed.
118+
///
119+
/// # Errors
120+
/// On a database error.
121+
pub async fn follow_renames(reach: &Reach) -> laravel::Result<usize> {
122+
let list: Vec<serde_json::Value> = reach
123+
.links
124+
.iter()
125+
.filter_map(|l| {
126+
let path = reach.paths.get(&(l.repository_id.clone(), l.installation.clone()))?;
127+
Some(serde_json::json!({
128+
"project": l.project_id, "url": l.url, "id": l.repository_id, "installation": l.installation,
129+
"path": path,
130+
}))
131+
})
132+
.collect();
133+
if list.is_empty() {
119134
return Ok(0);
120135
}
121-
let list = serde_json::Value::Array(
122-
reach
123-
.paths
124-
.iter()
125-
.map(|((id, installation), path)| serde_json::json!({ "id": id, "installation": installation, "path": path }))
126-
.collect(),
127-
)
128-
.to_string();
136+
let list = serde_json::Value::Array(list).to_string();
129137
// A GitHub project's URL is always on github.com: `Repository::parse` gives `forge = 'github'` only to github.com
130138
// (another `GITHUB_URL` is for testing and local only, `forge::check_github`), so the host is fixed here. The
131139
// picker's cache is updated in a data-modifying CTE, which Postgres runs whether or not the outer query reads it.
132140
let rows = db::query!(
133-
"WITH r AS (SELECT * FROM jsonb_to_recordset({list}::jsonb) AS x(id text, installation text, path text)), \
134-
picker AS (UPDATE user_repositories u SET full_name = r.path FROM r \
135-
WHERE u.repository_id = r.id AND u.installation_id = r.installation AND u.full_name <> r.path) \
141+
"WITH r AS (SELECT * FROM jsonb_to_recordset({list}::jsonb) \
142+
AS x(project bigint, url text, id text, installation text, path text)), \
143+
picker AS (UPDATE user_repositories u SET full_name = n.path \
144+
FROM (SELECT DISTINCT id, installation, path FROM r) n \
145+
WHERE u.repository_id = n.id AND u.installation_id = n.installation AND u.full_name <> n.path) \
136146
UPDATE projects p SET repository_url = 'https://github.com/' || r.path, updated_at = now() FROM r \
137-
WHERE p.forge = 'github' AND p.repository_id = r.id AND p.forge_installation = r.installation \
138-
AND p.deleted_at IS NULL AND p.repository_url IS DISTINCT FROM 'https://github.com/' || r.path \
147+
WHERE p.id = r.project AND p.forge = 'github' AND p.repository_id = r.id \
148+
AND p.forge_installation = r.installation AND p.deleted_at IS NULL \
149+
AND p.repository_url IS NOT DISTINCT FROM r.url \
150+
AND p.repository_url IS DISTINCT FROM 'https://github.com/' || r.path \
139151
RETURNING p.id, p.repository_url"
140152
)
141153
.select()

‎app/src/forge/webhooks.rs‎

Lines changed: 65 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,10 @@ pub enum ForgeEvent {
6363
repository: Repository,
6464
private: bool,
6565
},
66-
/// Renamed or transferred: the same repository (by ID) at a new URL.
66+
/// Renamed or transferred: the same repository (by ID) at a new URL, for the installation that sent it.
6767
Moved {
6868
repository: Repository,
69+
installation: String,
6970
},
7071
/// The account an installation is on was renamed (an `installation_target` delivery, action `renamed`): its
7172
/// repositories' URLs follow. GitHub sends no per-repository `renamed` delivery for an organization's rename.
@@ -204,7 +205,10 @@ pub fn read_event(kind: &str, event: &Value) -> Result<ForgeEvent, String> {
204205
},
205206
// The same repository at a new URL; links follow by its ID
206207
("repository", "renamed" | "transferred") => match repository(event) {
207-
Some(repository) if repository.id.is_some() => ForgeEvent::Moved { repository },
208+
Some(repository) if repository.id.is_some() => match installation {
209+
Some(installation) => ForgeEvent::Moved { repository, installation },
210+
None => ForgeEvent::Ignored,
211+
},
208212
_ => ForgeEvent::Ignored,
209213
},
210214
// The account the App is installed on was renamed: its repositories have new URLs
@@ -927,11 +931,14 @@ pub async fn handle(app: &GithubApp, event: ForgeEvent, claimed: bool) -> larave
927931
}
928932
json!({ "dispatched": projects.len() })
929933
}
930-
ForgeEvent::Moved { repository } => {
934+
ForgeEvent::Moved { repository, installation } => {
935+
// Only links through the installation that sent it, as the hourly sync: another installation's link to
936+
// the same repository ID may not cover its new owner
931937
let (id, url) = (repository.id.clone(), repository.url.clone());
932938
let moved = db::query!(
933939
"UPDATE projects SET repository_url = {url}, updated_at = now() \
934-
WHERE forge = 'github' AND repository_id = {id} AND repository_url IS DISTINCT FROM {url}"
940+
WHERE forge = 'github' AND repository_id = {id} AND forge_installation = {installation} \
941+
AND repository_url IS DISTINCT FROM {url}"
935942
)
936943
.update()
937944
.await?;
@@ -1019,10 +1026,10 @@ pub async fn handle(app: &GithubApp, event: ForgeEvent, claimed: bool) -> larave
10191026
///
10201027
/// A delivery can arrive late (the recovery job redelivers missed ones), after a newer rename: a late `acme→beta` after
10211028
/// `beta→acme` would move everything back to `beta`, and its logins can't tell it from a new rename. So GitHub is asked
1022-
/// what the account is called now (one call), and only a rename to that name is applied. Then the installation's login
1023-
/// changes only from `from` (any case), and URLs move only when it did, when it already reads `to` (a redelivery of the
1024-
/// rename just applied), or when VisualCI has no row for the installation (GitHub has just confirmed the new name, and
1025-
/// only URLs under `from` move).
1029+
/// what the account is called now (one call), and only a rename to that name is applied. Once GitHub has confirmed it,
1030+
/// the installation's login becomes GitHub's, whatever VisualCI had stored, and URLs move from both `from` and the
1031+
/// login VisualCI had: after quick renames (`acme→beta→gamma`, both delivered once GitHub says `gamma`, so the first is
1032+
/// ignored as stale) or a lost delivery, VisualCI still reads `acme` while this delivery says `beta`.
10261033
///
10271034
/// # Errors
10281035
/// When GitHub can't be asked (the delivery fails, so it's redelivered), or on a database error.
@@ -1033,37 +1040,42 @@ pub async fn account_renamed(
10331040
to: &str,
10341041
) -> laravel::Result<Option<u64>> {
10351042
let now = github_app::installation(app, installation).await?;
1036-
let current = now.as_ref().and_then(|i| i["account"]["login"].as_str());
1037-
if !current.is_some_and(|c| c.eq_ignore_ascii_case(to)) {
1038-
tracing::info!(installation, from, to, current, "a stale installation_target rename: ignored");
1043+
let Some(current) = now
1044+
.as_ref()
1045+
.and_then(|i| i["account"]["login"].as_str())
1046+
.filter(|c| c.eq_ignore_ascii_case(to) && login(c))
1047+
.map(str::to_string)
1048+
else {
1049+
tracing::info!(installation, from, to, "a stale installation_target rename: ignored");
10391050
return Ok(None);
1040-
}
1041-
let (id, from, to) = (installation.to_string(), from.to_lowercase(), to.to_string());
1042-
let renamed = db::query!(
1043-
"UPDATE github_installations SET account_login = {to}, updated_at = now() \
1044-
WHERE installation_id = {id} AND lower(account_login) = {from}"
1051+
};
1052+
let id = installation.to_string();
1053+
let from = from.to_lowercase();
1054+
let stored: Option<String> =
1055+
db::query!("SELECT account_login FROM github_installations WHERE installation_id = {id}").scalar().await?;
1056+
// The login VisualCI had, when there's a row: its URLs are under it if a delivery before this one was missed
1057+
let old = stored.map_or_else(|| from.clone(), |l| l.to_lowercase());
1058+
db::query!(
1059+
"UPDATE github_installations SET account_login = {current}, updated_at = now() \
1060+
WHERE installation_id = {id} AND account_login IS DISTINCT FROM {current}"
10451061
)
10461062
.update()
10471063
.await?;
1048-
if renamed == 0 {
1049-
let login: Option<String> =
1050-
db::query!("SELECT account_login FROM github_installations WHERE installation_id = {id}").scalar().await?;
1051-
if login.is_some_and(|l| !l.eq_ignore_ascii_case(&to)) {
1052-
tracing::info!(installation, from, to, "the installation's login isn't the rename's: ignored");
1053-
return Ok(None);
1054-
}
1055-
}
10561064
let moved = db::query!(
1057-
"UPDATE projects SET repository_url = 'https://github.com/' || {to} || '/' || split_part(repository_url, '/', 5), \
1065+
"UPDATE projects \
1066+
SET repository_url = 'https://github.com/' || {current} || '/' || split_part(repository_url, '/', 5), \
10581067
updated_at = now() \
10591068
WHERE forge = 'github' AND forge_installation = {id} AND deleted_at IS NULL \
1060-
AND split_part(repository_url, '/', 3) = 'github.com' AND lower(split_part(repository_url, '/', 4)) = {from}"
1069+
AND split_part(repository_url, '/', 3) = 'github.com' \
1070+
AND lower(split_part(repository_url, '/', 4)) IN ({from}, {old}) \
1071+
AND split_part(repository_url, '/', 4) <> {current}"
10611072
)
10621073
.update()
10631074
.await?;
10641075
db::query!(
1065-
"UPDATE user_repositories SET full_name = {to} || '/' || split_part(full_name, '/', 2) \
1066-
WHERE installation_id = {id} AND lower(split_part(full_name, '/', 1)) = {from}"
1076+
"UPDATE user_repositories SET full_name = {current} || '/' || split_part(full_name, '/', 2) \
1077+
WHERE installation_id = {id} AND lower(split_part(full_name, '/', 1)) IN ({from}, {old}) \
1078+
AND split_part(full_name, '/', 1) <> {current}"
10671079
)
10681080
.update()
10691081
.await?;
@@ -1151,6 +1163,17 @@ pub struct Reach {
11511163
/// (GitHub repository ID, installation) -> its `owner/name` now, which the hourly sync gives that installation's
11521164
/// links whose URL went stale. Only repositories whose collaborators the installation could list.
11531165
pub paths: HashMap<(String, String), String>,
1166+
/// Every linked project as it was read before GitHub was asked.
1167+
pub links: Vec<Link>,
1168+
}
1169+
1170+
/// A linked project's repository, installation and URL when [`reach`] read them.
1171+
#[derive(Debug)]
1172+
pub struct Link {
1173+
pub project_id: i64,
1174+
pub repository_id: String,
1175+
pub installation: String,
1176+
pub url: Option<String>,
11541177
}
11551178

11561179
/// List every linked repository's collaborators once: one installation token per installation, each repository's
@@ -1161,17 +1184,29 @@ pub struct Reach {
11611184
/// When GitHub can't answer for some repository (a partial answer would drop people), when its rate limit is low, or
11621185
/// on a database error.
11631186
pub async fn reach(app: &GithubApp) -> laravel::Result<Reach> {
1187+
// Each link's URL as it is before GitHub is asked, so the sync only replaces a URL nothing changed meanwhile
11641188
let rows = db::query!(
1165-
"SELECT DISTINCT repository_id, forge_installation FROM projects \
1166-
WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL AND deleted_at IS NULL"
1189+
"SELECT id, repository_id, forge_installation, repository_url FROM projects \
1190+
WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL AND deleted_at IS NULL \
1191+
ORDER BY repository_id, forge_installation, id"
11671192
)
11681193
.select()
11691194
.await?;
11701195
let mut tokens: HashMap<String, String> = HashMap::new();
11711196
let mut reach = Reach::default();
1197+
let mut asked = HashSet::new();
11721198
for r in rows {
11731199
let (repository_id, installation): (String, String) =
11741200
(r.try_get("repository_id")?, r.try_get("forge_installation")?);
1201+
reach.links.push(Link {
1202+
project_id: r.try_get("id")?,
1203+
repository_id: repository_id.clone(),
1204+
installation: installation.clone(),
1205+
url: r.try_get("repository_url")?,
1206+
});
1207+
if !asked.insert((repository_id.clone(), installation.clone())) {
1208+
continue;
1209+
}
11751210
let token = match tokens.get(&installation) {
11761211
Some(t) => t.clone(),
11771212
None => {

0 commit comments

Comments
 (0)