Skip to content

Backport sync team changes #1722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 64 additions & 10 deletions sync-team/src/github/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,46 @@ impl HttpClient {
}
}

/// Send a request to the GitHub API and return the response.
fn graphql<R, V>(&self, query: &str, variables: V, org: &str) -> anyhow::Result<R>
where
R: serde::de::DeserializeOwned,
V: serde::Serialize,
{
let res = self.send_graphql_req(query, variables, org)?;

if let Some(error) = res.errors.first() {
bail!("graphql error: {}", error.message);
}

read_graphql_data(res)
}

/// Send a request to the GitHub API and return the response.
/// If the request contains the error type `NOT_FOUND`, this method returns `Ok(None)`.
fn graphql_opt<R, V>(&self, query: &str, variables: V, org: &str) -> anyhow::Result<Option<R>>
where
R: serde::de::DeserializeOwned,
V: serde::Serialize,
{
let res = self.send_graphql_req(query, variables, org)?;

if let Some(error) = res.errors.first() {
if error.type_ == Some(GraphErrorType::NotFound) {
return Ok(None);
}
bail!("graphql error: {}", error.message);
}

read_graphql_data(res)
}

fn send_graphql_req<R, V>(
&self,
query: &str,
variables: V,
org: &str,
) -> anyhow::Result<GraphResult<R>>
where
R: serde::de::DeserializeOwned,
V: serde::Serialize,
Expand All @@ -105,19 +144,13 @@ impl HttpClient {
let resp = self
.req(Method::POST, &GitHubUrl::new("graphql", org))?
.json(&Request { query, variables })
.send()?
.send()
.context("failed to send graphql request")?
.custom_error_for_status()?;

let res: GraphResult<R> = resp.json_annotated().with_context(|| {
resp.json_annotated().with_context(|| {
format!("Failed to decode response body on graphql request with query '{query}'")
})?;
if let Some(error) = res.errors.first() {
bail!("graphql error: {}", error.message);
} else if let Some(data) = res.data {
Ok(data)
} else {
bail!("missing graphql data");
}
})
}

fn rest_paginated<F, T>(&self, method: &Method, url: &GitHubUrl, mut f: F) -> anyhow::Result<()>
Expand Down Expand Up @@ -159,6 +192,17 @@ impl HttpClient {
}
}

fn read_graphql_data<R>(res: GraphResult<R>) -> anyhow::Result<R>
where
R: serde::de::DeserializeOwned,
{
if let Some(data) = res.data {
Ok(data)
} else {
bail!("missing graphql data");
}
}

fn allow_not_found(resp: Response, method: Method, url: &str) -> Result<(), anyhow::Error> {
match resp.status() {
StatusCode::NOT_FOUND => {
Expand All @@ -180,9 +224,19 @@ struct GraphResult<T> {

#[derive(Debug, serde::Deserialize)]
struct GraphError {
#[serde(rename = "type")]
type_: Option<GraphErrorType>,
message: String,
}

#[derive(Debug, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum GraphErrorType {
NotFound,
#[serde(other)]
Other,
}

#[derive(serde::Deserialize)]
struct GraphNodes<T> {
nodes: Vec<Option<T>>,
Expand Down
22 changes: 13 additions & 9 deletions sync-team/src/github/api/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::github::api::{
BranchProtection, GraphNode, GraphNodes, GraphPageInfo, HttpClient, Login, Repo, RepoTeam,
RepoUser, Team, TeamMember, TeamRole, team_node_id, url::GitHubUrl, user_node_id,
};
use anyhow::Context as _;
use reqwest::Method;
use std::collections::{HashMap, HashSet};

Expand Down Expand Up @@ -271,16 +272,19 @@ impl GithubRead for GitHubApiRead {
is_archived: bool,
}

let result: Wrapper = self.client.graphql(
QUERY,
Params {
owner: org,
name: repo,
},
org,
)?;
let result: Option<Wrapper> = self
.client
.graphql_opt(
QUERY,
Params {
owner: org,
name: repo,
},
org,
)
.with_context(|| format!("failed to retrieve repo `{org}/{repo}`"))?;

let repo = result.repository.map(|repo_response| Repo {
let repo = result.and_then(|r| r.repository).map(|repo_response| Repo {
node_id: repo_response.id,
name: repo.to_string(),
description: repo_response.description.unwrap_or_default(),
Expand Down
18 changes: 10 additions & 8 deletions sync-team/src/github/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::github::tests::test_utils::{BranchProtectionBuilder, DataModel, RepoData, TeamData};
use crate::github::tests::test_utils::{
BranchProtectionBuilder, DEFAULT_ORG, DataModel, RepoData, TeamData,
};
use rust_team_data::v1::{BranchProtectionMode, RepoPermission};

mod test_utils;
Expand All @@ -17,7 +19,7 @@ fn team_create() {
let user = model.create_user("mark");
let user2 = model.create_user("jan");
let gh = model.gh_model();
model.create_team(TeamData::new("admins").gh_team("admins-gh", &[user, user2]));
model.create_team(TeamData::new("admins").gh_team(DEFAULT_ORG, "admins-gh", &[user, user2]));
let team_diff = model.diff_teams(gh);
insta::assert_debug_snapshot!(team_diff, @r###"
[
Expand Down Expand Up @@ -48,7 +50,7 @@ fn team_add_member() {
let mut model = DataModel::default();
let user = model.create_user("mark");
let user2 = model.create_user("jan");
model.create_team(TeamData::new("admins").gh_team("admins-gh", &[user]));
model.create_team(TeamData::new("admins").gh_team(DEFAULT_ORG, "admins-gh", &[user]));
let gh = model.gh_model();

model.get_team("admins").add_gh_member("admins-gh", user2);
Expand Down Expand Up @@ -85,11 +87,11 @@ fn team_dont_add_member_if_invitation_is_pending() {
let mut model = DataModel::default();
let user = model.create_user("mark");
let user2 = model.create_user("jan");
model.create_team(TeamData::new("admins").gh_team("admins-gh", &[user]));
model.create_team(TeamData::new("admins").gh_team(DEFAULT_ORG, "admins-gh", &[user]));
let mut gh = model.gh_model();

model.get_team("admins").add_gh_member("admins-gh", user2);
gh.add_invitation("admins-gh", "jan");
gh.add_invitation(DEFAULT_ORG, "admins-gh", "jan");

let team_diff = model.diff_teams(gh);
insta::assert_debug_snapshot!(team_diff, @"[]");
Expand All @@ -100,7 +102,7 @@ fn team_remove_member() {
let mut model = DataModel::default();
let user = model.create_user("mark");
let user2 = model.create_user("jan");
model.create_team(TeamData::new("admins").gh_team("admins-gh", &[user, user2]));
model.create_team(TeamData::new("admins").gh_team(DEFAULT_ORG, "admins-gh", &[user, user2]));
let gh = model.gh_model();

model
Expand Down Expand Up @@ -142,8 +144,8 @@ fn team_delete() {
// won't be generated, because no organization is known to scan for existing unmanaged teams.
model.create_team(
TeamData::new("admins")
.gh_team("admins-gh", &[user])
.gh_team("users-gh", &[user]),
.gh_team(DEFAULT_ORG, "admins-gh", &[user])
.gh_team(DEFAULT_ORG, "users-gh", &[user]),
);
let gh = model.gh_model();

Expand Down
Loading
Loading