diff --git a/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestNode.java b/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestNode.java new file mode 100644 index 0000000..abd61fa --- /dev/null +++ b/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestNode.java @@ -0,0 +1,50 @@ +package fr.zenika.opensource.stats.beans.gitlab.graphql; + +public class GitLabMergeRequestNode { + private String title; + private String webUrl; + private String state; + private String createdAt; + private GitLabMergeRequestProject project; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getWebUrl() { + return webUrl; + } + + public void setWebUrl(String webUrl) { + this.webUrl = webUrl; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(String createdAt) { + this.createdAt = createdAt; + } + + public GitLabMergeRequestProject getProject() { + return project; + } + + public void setProject(GitLabMergeRequestProject project) { + this.project = project; + } +} + diff --git a/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestProject.java b/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestProject.java new file mode 100644 index 0000000..5e7b51a --- /dev/null +++ b/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestProject.java @@ -0,0 +1,45 @@ +package fr.zenika.opensource.stats.beans.gitlab.graphql; + +public class GitLabMergeRequestProject { + private String name; + private String fullPath; + private String webUrl; + private String visibility; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFullPath() { + return fullPath; + } + + public void setFullPath(String fullPath) { + this.fullPath = fullPath; + } + + public String getWebUrl() { + return webUrl; + } + + public void setWebUrl(String webUrl) { + this.webUrl = webUrl; + } + + public String getVisibility() { + return visibility; + } + + public void setVisibility(String visibility) { + this.visibility = visibility; + } + + public boolean isPublic() { + return visibility == null || "public".equalsIgnoreCase(visibility); + } +} + diff --git a/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestsCount.java b/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestsCount.java index 5afa7f6..3a7a078 100644 --- a/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestsCount.java +++ b/src/main/java/fr/zenika/opensource/stats/beans/gitlab/graphql/GitLabMergeRequestsCount.java @@ -1,7 +1,10 @@ package fr.zenika.opensource.stats.beans.gitlab.graphql; +import java.util.List; + public class GitLabMergeRequestsCount { private int count; + private List nodes; public int getCount() { return count; @@ -10,4 +13,12 @@ public int getCount() { public void setCount(int count) { this.count = count; } + + public List getNodes() { + return nodes; + } + + public void setNodes(List nodes) { + this.nodes = nodes; + } } diff --git a/src/main/java/fr/zenika/opensource/stats/config/GitLabGraphQLQueries.java b/src/main/java/fr/zenika/opensource/stats/config/GitLabGraphQLQueries.java new file mode 100644 index 0000000..9439b04 --- /dev/null +++ b/src/main/java/fr/zenika/opensource/stats/config/GitLabGraphQLQueries.java @@ -0,0 +1,32 @@ +package fr.zenika.opensource.stats.config; + +public class GitLabGraphQLQueries { + + public static final String qGetMergedMergeRequestsForAPeriod = """ + query ($username: String!, $updatedAfter: Time, $updatedBefore: Time) { + user(username: $username) { + authoredMergeRequests( + state: merged + updatedAfter: $updatedAfter + updatedBefore: $updatedBefore + first: 100 + ) { + count + nodes { + title + webUrl + state + createdAt + project { + name + fullPath + webUrl + visibility + } + } + } + } + } + """; +} + diff --git a/src/main/java/fr/zenika/opensource/stats/services/GitLabServices.java b/src/main/java/fr/zenika/opensource/stats/services/GitLabServices.java index 4073442..bd8e6b2 100644 --- a/src/main/java/fr/zenika/opensource/stats/services/GitLabServices.java +++ b/src/main/java/fr/zenika/opensource/stats/services/GitLabServices.java @@ -1,13 +1,20 @@ package fr.zenika.opensource.stats.services; import io.quarkus.logging.Log; +import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; +import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClientBuilder; import fr.zenika.opensource.stats.beans.ContributionDetail; import fr.zenika.opensource.stats.beans.CustomStatsContributionsUserByMonth; -import fr.zenika.opensource.stats.beans.gitlab.GitLabEvent; import fr.zenika.opensource.stats.beans.gitlab.GitLabMember; import fr.zenika.opensource.stats.beans.gitlab.GitLabMergeRequest; import fr.zenika.opensource.stats.beans.gitlab.GitLabProject; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabGraphQLUser; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabMergeRequestNode; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabMergeRequestProject; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabMergeRequestsCount; import fr.zenika.opensource.stats.config.GitLabClient; +import fr.zenika.opensource.stats.config.GitLabGraphQLQueries; +import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.GenericType; @@ -20,9 +27,9 @@ import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Locale; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @@ -30,16 +37,27 @@ @ApplicationScoped public class GitLabServices { - private static final int NB_MRS_PER_PAGE = 100; - @Inject @RestClient GitLabClient gitLabClient; + @ConfigProperty(name = "quarkus.smallrye-graphql-client.gitlab-api.url", defaultValue = "https://gitlab.com/api/graphql") + String graphQLUrl; + @Inject @ConfigProperty(name = "gitlab.token") Optional gitlabToken; + DynamicGraphQLClient dynamicGraphQLClient; + + @PostConstruct + public void init() { + dynamicGraphQLClient = DynamicGraphQLClientBuilder.newBuilder() + .url(graphQLUrl) + .header("Authorization", getAuthHeader()) + .build(); + } + private String getAuthHeader() { return "Bearer " + gitlabToken.orElse(""); } @@ -81,38 +99,26 @@ public List getPersonalProjectsForAnUser(String username) { * @return A list of monthly contribution stats. */ public List getContributionsForTheCurrentYear(String username, int year) { - return getUserInformation(username) - .map(user -> getContributionsByUserId(user.getId(), username, year)) - .orElse(List.of()); + if (username == null || username.isBlank()) { + return List.of(); + } + return getContributionsByUserId(null, username, year); } /** - * Get contributions for a specific GitLab user ID. + * Get contributions for a specific GitLab user. * - * @param userId The numeric GitLab user ID. - * @param username The username (for logging). + * @param userId The numeric GitLab user ID (optional when using GraphQL by username). + * @param username The GitLab username. * @param year The year. * @return A list of monthly contribution stats. */ public List getContributionsByUserId(String userId, String username, int year) { - List result = new ArrayList<>(); - - // If userId is not numeric, it might be a username from old data. Try to - // resolve it. - String actualId = userId; - if (userId != null && !userId.matches("\\d+")) { - Log.warn("GitLab ID '" + userId + "' for " + username - + " is not numeric. Attempting to resolve ID from username."); - Optional user = getUserInformation(username); - if (user.isPresent()) { - actualId = user.get().getId(); - Log.info("Resolved GitLab username '" + username + "' to ID '" + actualId + "'"); - } else { - Log.error("Failed to resolve GitLab ID for username '" + username + "'. Aborting contribution fetch."); - return List.of(); - } + if (username == null || username.isBlank()) { + return List.of(); } + List result = new ArrayList<>(); for (Month month : Month.values()) { if (year == LocalDate.now().getYear() && month.getValue() > LocalDate.now().getMonthValue()) { @@ -126,25 +132,32 @@ public List getContributionsByUserId(String String updatedBefore = endOfMonth.atTime(23, 59, 59).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "Z"; try { - // To fetch only public contributions, do not send Authorization header (unauthenticated search) - // Use scope=all to see MRs across all public projects - // Use updated_after/before for better compatibility with older GitLab versions - Response response = gitLabClient.getMergeRequests(actualId, "merged", updatedAfter, updatedBefore, - "all", NB_MRS_PER_PAGE); - String totalStr = response.getHeaderString("X-Total"); - List details = extractGitLabContributionDetails(response); - - int total = Optional.ofNullable(totalStr) - .filter(s -> !s.isEmpty()) - .map(Integer::parseInt) - .orElse(details.size()); + var variables = new HashMap(); + variables.put("username", username); + variables.put("updatedAfter", updatedAfter); + variables.put("updatedBefore", updatedBefore); + + io.smallrye.graphql.client.Response gqlResponse = dynamicGraphQLClient.executeSync( + GitLabGraphQLQueries.qGetMergedMergeRequestsForAPeriod, + variables); + + GitLabGraphQLUser userStats = Optional.ofNullable(gqlResponse) + .map(r -> r.getObject(GitLabGraphQLUser.class, "user")) + .orElse(null); + + GitLabMergeRequestsCount mrContributions = Optional.ofNullable(userStats) + .map(GitLabGraphQLUser::getAuthoredMergeRequests) + .orElse(null); + + List details = extractGitLabGraphQLContributionDetails(mrContributions); + int total = details.size(); result.add(new CustomStatsContributionsUserByMonth( month.getValue(), month.getDisplayName(TextStyle.FULL, Locale.ENGLISH), total, details)); - Log.info("Fetching GitLab merged MRs for " + username + " (ID: " + actualId + ") in " + month + " " + Log.info("Fetching GitLab merged MRs for " + username + " in " + month + " " + year + " | " + total); } catch (Exception e) { @@ -158,6 +171,34 @@ public List getContributionsByUserId(String return result; } + List extractGitLabGraphQLContributionDetails(GitLabMergeRequestsCount mrContributions) { + return Optional.ofNullable(mrContributions) + .map(GitLabMergeRequestsCount::getNodes) + .orElse(List.of()) + .stream() + .filter(Objects::nonNull) + .filter(mr -> Optional.ofNullable(mr.getProject()) + .map(GitLabMergeRequestProject::isPublic) + .orElse(true)) + .map(this::mapMergeRequestNodeToDetail) + .collect(Collectors.toList()); + } + + private ContributionDetail mapMergeRequestNodeToDetail(GitLabMergeRequestNode mr) { + Optional projOpt = Optional.ofNullable(mr.getProject()); + String projectName = projOpt.map(GitLabMergeRequestProject::getName).orElse(""); + String projectFullName = projOpt.map(GitLabMergeRequestProject::getFullPath).orElse(projectName); + String projectUrl = projOpt.map(GitLabMergeRequestProject::getWebUrl).orElse(""); + return new ContributionDetail( + projectName, + projectFullName, + projectUrl, + Optional.ofNullable(mr.getTitle()).orElse(""), + Optional.ofNullable(mr.getWebUrl()).orElse(""), + Optional.ofNullable(mr.getState()).orElse(""), + Optional.ofNullable(mr.getCreatedAt()).orElse("")); + } + List extractGitLabContributionDetails(Response response) { if (response == null || !response.hasEntity()) { return List.of(); diff --git a/src/test/java/fr/zenika/opensource/stats/services/GitLabServicesTest.java b/src/test/java/fr/zenika/opensource/stats/services/GitLabServicesTest.java index fd6bfce..9467e9f 100644 --- a/src/test/java/fr/zenika/opensource/stats/services/GitLabServicesTest.java +++ b/src/test/java/fr/zenika/opensource/stats/services/GitLabServicesTest.java @@ -1,10 +1,16 @@ package fr.zenika.opensource.stats.services; +import fr.zenika.opensource.stats.beans.ContributionDetail; import fr.zenika.opensource.stats.beans.CustomStatsContributionsUserByMonth; import fr.zenika.opensource.stats.beans.gitlab.GitLabMember; import fr.zenika.opensource.stats.beans.gitlab.GitLabProject; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabGraphQLUser; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabMergeRequestNode; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabMergeRequestProject; +import fr.zenika.opensource.stats.beans.gitlab.graphql.GitLabMergeRequestsCount; import fr.zenika.opensource.stats.config.GitLabClient; -import jakarta.ws.rs.core.Response; +import fr.zenika.opensource.stats.config.GitLabGraphQLQueries; +import io.smallrye.graphql.client.dynamic.api.DynamicGraphQLClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; @@ -16,8 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -28,6 +33,9 @@ class GitLabServicesTest { @Mock GitLabClient gitLabClient; + @Mock + DynamicGraphQLClient dynamicGraphQLClient; + @InjectMocks GitLabServices gitLabServices; @@ -69,17 +77,102 @@ void getPersonalProjectsForAnUser_ShouldOnlyReturnPublicNonForkProjects() { } @Test - void getContributionsByUserId_ShouldQueryWithoutAuthHeaderForPublicMRs() { - Response response = mock(Response.class); - when(response.getHeaderString("X-Total")).thenReturn("5"); - - when(gitLabClient.getMergeRequests(eq("3589694"), eq("merged"), anyString(), anyString(), eq("all"), eq(100))) - .thenReturn(response); + void getContributionsByUserId_ShouldQueryGraphQLAndFilterOnlyPublicMRs() throws Exception { + GitLabMergeRequestProject publicProject = new GitLabMergeRequestProject(); + publicProject.setName("communities-api"); + publicProject.setFullPath("communities-api/communities-api"); + publicProject.setWebUrl("https://gitlab.com/communities-api/communities-api"); + publicProject.setVisibility("public"); + + GitLabMergeRequestNode publicMr = new GitLabMergeRequestNode(); + publicMr.setTitle("feat: public mr"); + publicMr.setWebUrl("https://gitlab.com/communities-api/communities-api/-/merge_requests/1"); + publicMr.setState("merged"); + publicMr.setCreatedAt("2026-01-10T10:00:00Z"); + publicMr.setProject(publicProject); + + GitLabMergeRequestProject privateProject = new GitLabMergeRequestProject(); + privateProject.setName("arbregen"); + privateProject.setFullPath("arbre-gen/arbregen"); + privateProject.setWebUrl("https://gitlab.com/arbre-gen/arbregen"); + privateProject.setVisibility("private"); + + GitLabMergeRequestNode privateMr = new GitLabMergeRequestNode(); + privateMr.setTitle("chore: private mr"); + privateMr.setWebUrl("https://gitlab.com/arbre-gen/arbregen/-/merge_requests/2"); + privateMr.setState("merged"); + privateMr.setCreatedAt("2026-01-11T10:00:00Z"); + privateMr.setProject(privateProject); + + GitLabMergeRequestsCount mrContributions = new GitLabMergeRequestsCount(); + mrContributions.setCount(2); + mrContributions.setNodes(List.of(publicMr, privateMr)); + + GitLabGraphQLUser gqlUser = new GitLabGraphQLUser(); + gqlUser.setAuthoredMergeRequests(mrContributions); + + io.smallrye.graphql.client.Response gqlResponse = mock(io.smallrye.graphql.client.Response.class); + when(gqlResponse.getObject(GitLabGraphQLUser.class, "user")).thenReturn(gqlUser); + + when(dynamicGraphQLClient.executeSync(eq(GitLabGraphQLQueries.qGetMergedMergeRequestsForAPeriod), anyMap())) + .thenReturn(gqlResponse); List result = gitLabServices.getContributionsByUserId("3589694", "jeanphi", 2026); assertTrue(result.size() > 0); - assertEquals(5, result.get(0).getContributions()); - verify(gitLabClient, org.mockito.Mockito.atLeastOnce()).getMergeRequests(eq("3589694"), eq("merged"), anyString(), anyString(), eq("all"), eq(100)); + assertEquals(1, result.get(0).getContributions()); + List details = result.get(0).getContributionsDetails(); + assertEquals(1, details.size()); + assertEquals("communities-api/communities-api", details.get(0).getProjectFullName()); + verify(dynamicGraphQLClient, org.mockito.Mockito.atLeastOnce()) + .executeSync(eq(GitLabGraphQLQueries.qGetMergedMergeRequestsForAPeriod), anyMap()); + } + + @Test + void graphqlResponseDeserialization_ShouldFilterPrivateProject() { + String json = """ + { + "data": { + "user": { + "authoredMergeRequests": { + "count": 2, + "nodes": [ + { + "title": "feat: private mr", + "webUrl": "https://gitlab.com/arbre-gen/arbregen/-/merge_requests/277", + "state": "merged", + "createdAt": "2025-12-30T07:44:02Z", + "project": { + "name": "arbregen", + "fullPath": "arbre-gen/arbregen", + "webUrl": "https://gitlab.com/arbre-gen/arbregen", + "visibility": "private" + } + }, + { + "title": "feat: public mr", + "webUrl": "https://gitlab.com/communities-api/communities-api/-/merge_requests/298", + "state": "merged", + "createdAt": "2026-11-02T07:05:16Z", + "project": { + "name": "communities-api", + "fullPath": "communities-api/communities-api", + "webUrl": "https://gitlab.com/communities-api/communities-api", + "visibility": "public" + } + } + ] + } + } + } + } + """; + io.smallrye.graphql.client.Response response = io.smallrye.graphql.client.impl.ResponseReader.readFrom(json, null); + GitLabGraphQLUser userStats = response.getObject(GitLabGraphQLUser.class, "user"); + List details = gitLabServices.extractGitLabGraphQLContributionDetails(userStats.getAuthoredMergeRequests()); + + assertEquals(1, details.size()); + assertEquals("communities-api/communities-api", details.get(0).getProjectFullName()); + assertEquals("communities-api", details.get(0).getProjectName()); } }