Skip to content
TypeScript

fix(gitlab): the checks and review list filters work (#30433)

Antonyfab95f38a580
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 279642674b7..7a43394c2a2 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -3614,7 +3614,7 @@ it.effect("hands a host's own resume position back on the next read", () =>
}),
);
-it.effect("judges the review filter only on a host that summarises its reviews", () =>
+it.effect("judges review and checks filters only on a host that summarises them", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [
@@ -3632,10 +3632,15 @@ it.effect("judges the review filter only on a host that summarises its reviews",
listChangeRequests: () =>
Effect.succeed({
items: [
- { ...changeRequest(1, "2026-07-02T00:00:00Z"), reviewDecision: null },
+ {
+ ...changeRequest(1, "2026-07-02T00:00:00Z"),
+ reviewDecision: null,
+ checksState: "failing" as const,
+ },
{
...changeRequest(2, "2026-07-02T00:00:00Z"),
reviewDecision: "approved" as const,
+ checksState: null,
},
],
truncated: false,
@@ -3658,6 +3663,12 @@ it.effect("judges the review filter only on a host that summarises its reviews",
const approved = yield* service.list({ state: "open", filters: { review: "approved" } });
assert.deepStrictEqual(approved.entries.map((entry) => entry.number).toSorted(), [2, 3]);
+
+ const failing = yield* service.list({ state: "open", filters: { checks: "failing" } });
+ assert.deepStrictEqual(failing.entries.map((entry) => entry.number).toSorted(), [1, 3]);
+
+ const passing = yield* service.list({ state: "open", filters: { checks: "passing" } });
+ assert.deepStrictEqual(passing.entries.map((entry) => entry.number).toSorted(), [3]);
}),
);
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 89986c7fa78..6600f6810bc 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -1197,7 +1197,6 @@ export const make = Effect.gen(function* () {
{ concurrency: REPOSITORY_CONCURRENCY },
);
- // Only the host can filter checks; listed rows have no check state.
const matchesRowFilters = (
item: ProviderChangeRequest,
filters: PullRequestListFilters | undefined,
@@ -1213,6 +1212,9 @@ export const make = Effect.gen(function* () {
(filters.review === "none"
? item.reviewDecision === null
: item.reviewDecision === filters.review)) &&
+ (filters.checks === undefined ||
+ item.checksState === undefined ||
+ item.checksState === filters.checks) &&
(filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
(filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
(filters.author === undefined ||
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
index 0e62a3a615a..199e849af0a 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
@@ -114,6 +114,40 @@ function callAt(index: number) {
return call[0];
}
+function graphqlListPage(
+ numbers: ReadonlyArray<number>,
+ pageInfo: { readonly hasNextPage: boolean; readonly endCursor: string | null },
+): string {
+ return JSON.stringify({
+ data: {
+ metadata: { enterprise: true },
+ project: {
+ mergeRequests: {
+ pageInfo,
+ nodes: numbers.map((number) => ({
+ iid: String(number),
+ title: `Merge request ${number}`,
+ webUrl: `https://gitlab.com/acme/web/-/merge_requests/${number}`,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ sourceBranch: "feat/page",
+ targetBranch: "main",
+ approved: true,
+ approvedBy: { nodes: [{ username: "julius" }] },
+ })),
+ },
+ },
+ },
+ });
+}
+
+function graphqlRequestOf(index: number) {
+ return JSON.parse(callAt(index).stdin ?? "{}") as {
+ readonly query: string;
+ readonly variables: Record<string, unknown>;
+ };
+}
+
afterEach(() => {
mockedExecute.mockReset();
});
@@ -144,16 +178,16 @@ layer("GitLabPullRequestCli.layer", (it) => {
});
const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
const reference = { cwd: "/w", repository: "acme/web", host: "gitlab.internal" };
- expect(yield* cli.getReviewDecisions({ ...reference, numbers: [] })).toEqual(new Map());
+ expect(yield* cli.getListStates({ ...reference, numbers: [] })).toEqual(new Map());
expect(mockedExecute).not.toHaveBeenCalled();
- const decisions = yield* cli.getReviewDecisions({
+ const decisions = yield* cli.getListStates({
...reference,
numbers: Array.from({ length: 101 }, (_, index) => index + 1),
});
expect(callAt(0).host).toBe(reference.host);
expect(callAt(1).host).toBe(reference.host);
expect(decisions.size).toBe(101);
- expect(decisions.get(101)).toBe("approved");
+ expect(decisions.get(101)).toEqual({ reviewDecision: "approved", checksState: null });
expect(mockedExecute).toHaveBeenCalledTimes(2);
expect(
[0, 1].map((index) => JSON.parse(callAt(index).stdin ?? "{}").variables.iids.length),
@@ -238,6 +272,7 @@ layer("GitLabPullRequestCli.layer", (it) => {
excludedLabels: ["wontfix", "stale", "any"],
author: "@me",
draft: "only",
+ review: "approved",
},
});
@@ -246,6 +281,195 @@ layer("GitLabPullRequestCli.layer", (it) => {
expect(params.get("not[labels]")).toBe("wontfix,stale");
expect(params.get("author_username")).toBe("bilal");
expect(params.get("wip")).toBe("yes");
+ expect(params.get("approved_by_usernames[]")).toBe("Any");
+ }),
+ );
+
+ it.effect("narrows by approval only where GitLab returns every row the decision keeps", () =>
+ Effect.gen(function* () {
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ const reviews = ["none", "review-required", "changes-requested"] as const;
+ for (const review of reviews) {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))));
+ yield* cli.listMergeRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ filters: { review },
+ });
+ }
+
+ const sent = reviews.map((_, call) => {
+ const params = new URLSearchParams((argsOfCall(call)[1] ?? "").split("?")[1]);
+ return [params.get("approved_by_ids[]"), params.get("approved_by_usernames[]")];
+ });
+ expect(sent).toEqual([
+ ["None", null],
+ [null, null],
+ [null, null],
+ ]);
+ }),
+ );
+
+ it.effect(
+ "lists through GraphQL with the filters GitLab narrows there, declaring only those",
+ () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValue(
+ Effect.succeed(output(graphqlListPage([1], { hasNextPage: false, endCursor: null }))),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.listMergeRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ query: " page ",
+ graphql: true,
+ cursor: {
+ updatedBefore: "2026-07-03T00:00:00Z",
+ delivered: 10,
+ resumeAfter: "eyJpZCI6IjEifQ",
+ },
+ filters: {
+ labels: [["bug"], ["size:S", "size:XS"]],
+ excludedLabels: ["wontfix"],
+ author: "octocat",
+ draft: "hide",
+ review: "changes-requested",
+ },
+ });
+
+ const { query, variables } = graphqlRequestOf(0);
+ expect(variables).toEqual({
+ fullPath: "acme/web",
+ first: 10,
+ after: "eyJpZCI6IjEifQ",
+ state: "opened",
+ authorUsername: "octocat",
+ search: "page",
+ labels: ["bug"],
+ draft: false,
+ reviewStates: ["REQUESTED_CHANGES"],
+ notLabels: ["wontfix"],
+ });
+ expect(query).toContain("reviewStates: $reviewStates");
+ expect(query).toContain("not: { labels: $notLabels }");
+ expect(query).not.toContain("$approvedBy");
+
+ // Beside a reviewer, GitLab would match only that reviewer's own state.
+ yield* cli.listMergeRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ state: "open",
+ involvement: "reviewing",
+ viewer: "bilal",
+ limit: 10,
+ graphql: true,
+ filters: { review: "changes-requested" },
+ });
+ expect(graphqlRequestOf(1).variables).toMatchObject({ reviewerUsername: "bilal" });
+ expect(graphqlRequestOf(1).variables).not.toHaveProperty("reviewStates");
+ }),
+ );
+
+ it.effect("walks GraphQL pages by GitLab's cursor and hands the last one back", () =>
+ Effect.gen(function* () {
+ mockedExecute
+ .mockReturnValueOnce(
+ Effect.succeed(output(graphqlListPage([1, 2], { hasNextPage: true, endCursor: "c1" }))),
+ )
+ .mockReturnValueOnce(
+ Effect.succeed(output(graphqlListPage([3], { hasNextPage: true, endCursor: "c2" }))),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ const batch = yield* cli.listMergeRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 3,
+ graphql: true,
+ filters: { review: "approved" },
+ });
+
+ expect(batch).toMatchObject({ truncated: true, cursorAdvance: 3, resumeAfter: "c2" });
+ expect(batch.items.map((item) => item.number)).toEqual([1, 2, 3]);
+ expect(batch.listStates?.get(3)).toEqual({ reviewDecision: "approved", checksState: null });
+ expect([0, 1].map((call) => graphqlRequestOf(call).variables)).toMatchObject([
+ { first: 3, after: null, approvedBy: ["Any"] },
+ { first: 1, after: "c1" },
+ ]);
+ }),
+ );
+
+ it.effect("reads REST for a REST cursor, and when a first GraphQL read or command fails", () =>
+ Effect.gen(function* () {
+ mockedExecute
+ .mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))))
+ .mockReturnValueOnce(
+ Effect.succeed(
+ output(JSON.stringify({ errors: [{ message: "Field 'search' doesn't exist" }] })),
+ ),
+ )
+ .mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 1))))
+ .mockReturnValueOnce(Effect.succeed(output(JSON.stringify({ errors: [] }))))
+ .mockReturnValueOnce(
+ Effect.fail(
+ new GitLabCli.GitLabCliCommandError({
+ operation: "execute",
+ command: "glab",
+ cwd: "/w",
+ cause: new Error("502 Bad Gateway"),
+ }),
+ ),
+ )
+ .mockReturnValueOnce(Effect.succeed(output(mergeRequests(1, 2))));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ const list = (cursor?: { updatedBefore: string; delivered: number; resumeAfter?: string }) =>
+ cli.listMergeRequests({
+ cwd: "/w",
+ repository: "acme/web",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ // A cursor, not the host's current answer, picks the API.
+ graphql: cursor?.resumeAfter === undefined,
+ ...(cursor === undefined ? {} : { cursor }),
+ });
+
+ yield* list({ updatedBefore: "2026-07-03T00:00:00Z", delivered: 10 });
+ const fellBack = yield* list();
+ // A resumed GraphQL read stays on GraphQL and fails, since REST would read `delivered` as an offset.
+ const resumed = yield* Effect.result(
+ list({ updatedBefore: "2026-07-03T00:00:00Z", delivered: 10, resumeAfter: "c1" }),
+ );
+ const commandFailed = yield* list();
+
+ expect(fellBack.items.map((item) => item.number)).toEqual([1]);
+ expect(fellBack).not.toHaveProperty("resumeAfter");
+ expect(mockedExecute.mock.calls.map(([request]) => request.args[1]?.split("?")[0])).toEqual([
+ "projects/acme%2Fweb/merge_requests",
+ "graphql",
+ "projects/acme%2Fweb/merge_requests",
+ "graphql",
+ "graphql",
+ "projects/acme%2Fweb/merge_requests",
+ ]);
+ expect(commandFailed.items.map((item) => item.number)).toEqual([2]);
+ expect(resumed).toMatchObject({
+ _tag: "Failure",
+ failure: { _tag: "GitLabMergeRequestReadError" },
+ });
}),
);
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index ece38c97dbc..7c038480328 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -24,7 +24,6 @@ import type {
PullRequestReaction,
PullRequestReactionContent,
PullRequestReviewCommentDraft,
- PullRequestReviewDecision,
PullRequestReviewPosition,
PullRequestReviewThread,
PullRequestReviewVerdict,
@@ -46,6 +45,8 @@ import {
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
decodeMergeRequestChangesJson,
+ decodeGraphqlListSupportJson,
+ decodeMergeRequestGraphqlListJson,
decodeMergeRequestListJson,
decodeMergeRequestFileStatsJson,
decodeMergeRequestStatsJson,
@@ -55,7 +56,7 @@ import {
decodeProjectLabelsJson,
decodeProjectUsersJson,
decodeRepositoryBlobsJson,
- decodeReviewDecisionsJson,
+ decodeListStatesJson,
decodeSourceBranchJson,
decodeTriggerJobChecksJson,
decodeViewerJson,
@@ -65,11 +66,14 @@ import {
MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
MERGE_REQUEST_STATS_GRAPHQL_QUERY,
REPOSITORY_BLOBS_GRAPHQL_QUERY,
- REVIEW_DECISIONS_GRAPHQL_QUERY,
+ LIST_ITEM_GRAPHQL_FIELDS,
+ LIST_STATES_GRAPHQL_QUERY,
+ SERVER_VERSION_GRAPHQL_QUERY,
SOURCE_BRANCH_GRAPHQL_QUERY,
type GitLabDiffRefs,
type GitLabMergeRequestDetail,
type GitLabMergeRequestListItem,
+ type GitLabMergeRequestListState,
type GitLabProjectUsers,
} from "./gitLabMergeRequestJson.ts";
import type {
@@ -283,6 +287,10 @@ export interface GitLabMergeRequestListBatch {
readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
readonly truncated: boolean;
readonly cursorAdvance: number;
+ /** GitLab's GraphQL cursor past the last row, when the page was read through GraphQL. */
+ readonly resumeAfter?: string;
+ /** Present when the read already carried each row's approval and pipeline state. */
+ readonly listStates?: ReadonlyMap<number, GitLabMergeRequestListState>;
}
export interface GitLabMergeRequestDiffSlice {
@@ -310,8 +318,19 @@ export class GitLabPullRequestCli extends Context.Service<
readonly query?: string | undefined;
readonly cursor?: ProviderListCursor | undefined;
readonly filters?: PullRequestListFilters | undefined;
+ /**
+ * Read a first page through GraphQL, which narrows more filters; see `supportsGraphqlList`.
+ * A cursor keeps the API that handed it out.
+ */
+ readonly graphql?: boolean;
}) => Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError>;
+ /** Whether this host's GraphQL list takes every filter the REST list does. */
+ readonly supportsGraphqlList: (input: {
+ readonly cwd: string;
+ readonly host?: string | undefined;
+ }) => Effect.Effect<boolean, GitLabPullRequestCliError>;
+
readonly getMergeRequestDetail: (input: {
readonly cwd: string;
readonly host?: string | undefined;
@@ -321,13 +340,14 @@ export class GitLabPullRequestCli extends Context.Service<
readonly downstreamChecks?: boolean;
}) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;
- readonly getReviewDecisions: (input: {
+ /** Approval and head pipeline state, read in one GraphQL request per 100 merge requests. */
+ readonly getListStates: (input: {
readonly cwd: string;
readonly host?: string | undefined;
readonly repository: string;
readonly numbers: ReadonlyArray<number>;
}) => Effect.Effect<
- ReadonlyMap<number, PullRequestReviewDecision | null>,
+ ReadonlyMap<number, GitLabMergeRequestListState>,
GitLabPullRequestCliError
>;
@@ -605,7 +625,19 @@ function involvementParams(input: {
* GitLab's `labels` asks for every label it names, so only groups of one go to it; a group of
* alternatives is left for the service to narrow. A comma would split a name in two, and `None`
* and `Any` mean "unlabeled" and "labeled" to GitLab rather than labels of those names.
+ * Review filters go only where GitLab returns every row the service's exact filter keeps.
*/
+function listableLabels(filters: PullRequestListFilters) {
+ const listable = (names: ReadonlyArray<string>) =>
+ names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim()));
+ return {
+ required: listable(
+ (filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])),
+ ),
+ excluded: listable(filters.excludedLabels ?? []),
+ };
+}
+
function filterParams(input: {
readonly filters?: PullRequestListFilters | undefined;
readonly involvement: PullRequestInvolvement;
@@ -613,12 +645,7 @@ function filterParams(input: {
}): ReadonlyArray<readonly [string, string]> {
const filters = input.filters;
if (filters === undefined) return [];
- const listable = (names: ReadonlyArray<string>) =>
- names.filter((name) => !name.includes(",") && !/^(?:none|any)$/iu.test(name.trim()));
- const required = listable(
- (filters.labels ?? []).flatMap((group) => (group.length === 1 ? group : [])),
- );
- const excluded = listable(filters.excludedLabels ?? []);
+ const { required, excluded } = listableLabels(filters);
return [
...(required.length === 0 ? [] : [["labels", required.join(",")] as const]),
...(excluded.length === 0 ? [] : [["not[labels]", excluded.join(",")] as const]),
@@ -633,9 +660,92 @@ function filterParams(input: {
...(filters.draft === undefined
? []
: [["wip", filters.draft === "only" ? "yes" : "no"] as const]),
+ ...(filters.review === "approved"
+ ? [["approved_by_usernames[]", "Any"] as const]
+ : filters.review === "none"
+ ? [["approved_by_ids[]", "None"] as const]
+ : []),
];
}
+/**
+ * The GraphQL list takes the REST filters and narrows two review filters exactly: `approvedBy`
+ * Any for approved, and reviewer states for changes requested. Only arguments in use are
+ * declared, since GraphQL rejects a declared variable the query never reads.
+ */
+function graphqlListQuery(input: {
+ readonly repository: string;
+ readonly state: PullRequestListState;
+ readonly involvement: PullRequestInvolvement;
+ readonly viewer: string;
+ readonly query?: string | undefined;
+ readonly filters?: PullRequestListFilters | undefined;
+ readonly first: number;
+ readonly after: string | undefined;
+}): { readonly query: string; readonly variables: Record<string, unknown> } {
+ const filters = input.filters ?? {};
+ const { required, excluded } = listableLabels(filters);
+ const search = input.query?.trim() ?? "";
+ const author =
+ input.involvement === "authored"
+ ? input.viewer
+ : filters.author === undefined
+ ? undefined
+ : resolvePullRequestAuthorFilter(filters.author, input.viewer);
+ const args: ReadonlyArray<readonly [name: string, type: string, value: unknown]> = [
+ ["state", "MergeRequestState", stateParam(input.state)],
+ ...(author === undefined ? [] : [["authorUsername", "String", author] as const]),
+ ...(input.involvement === "reviewing"
+ ? [["reviewerUsername", "String", input.viewer] as const]
+ : []),
+ ...(search.length === 0 ? [] : [["search", "String", search] as const]),
+ ...(required.length === 0 ? [] : [["labels", "[String!]", required] as const]),
+ ...(filters.draft === undefined
+ ? []
+ : [["draft", "Boolean", filters.draft === "only"] as const]),
+ ...(filters.review === "approved" ? [["approvedBy", "[String!]", ["Any"]] as const] : []),
+ // Beside `reviewerUsername`, GitLab matches review states on that reviewer alone.
+ ...(filters.review === "changes-requested" && input.involvement !== "reviewing"
+ ? [["reviewStates", "[MergeRequestReviewState!]", ["REQUESTED_CHANGES"]] as const]
+ : []),
+ ];
+ const declarations = [
+ "$fullPath: ID!",
+ "$first: Int!",
+ "$after: String",
+ ...args.map(([name, type]) => `$${name}: ${type}`),
+ ...(excluded.length === 0 ? [] : ["$notLabels: [String!]"]),
+ ];
+ const usages = [
+ "sort: UPDATED_DESC",
+ "first: $first",
+ "after: $after",
+ ...args.map(([name]) => `${name}: $${name}`),
+ ...(excluded.length === 0 ? [] : ["not: { labels: $notLabels }"]),
+ ];
+ return {
+ query: `query(${declarations.join(", ")}) {
+ metadata { enterprise }
+ project(fullPath: $fullPath) {
+ mergeRequests(${usages.join(", ")}) {
+ pageInfo { hasNextPage endCursor }
+ nodes { ${LIST_ITEM_GRAPHQL_FIELDS} }
+ }
+ }
+}`,
+ variables: {
+ fullPath: input.repository.trim(),
+ first: input.first,
+ after: input.after ?? null,
+ ...Object.fromEntries(args.map(([name, , value]) => [name, value])),
+ ...(excluded.length === 0 ? {} : { notLabels: excluded }),
+ },
+ };
+}
+
+/** The list cursor carries GitLab's own position only when it fits the cursor's alphabet. */
+const RESUME_AFTER_PATTERN = /^[\w.:~+-]{1,128}$/u;
+
function diffCursorPage(cursor: string): number | null {
return /^[1-9][0-9]{0,6}$/.test(cursor) ? Number(cursor) : null;
}
@@ -1300,6 +1410,66 @@ export const make = Effect.gen(function* () {
}),
);
+ const graphqlListPage = (input: {
+ readonly cwd: string;
+ readonly host?: string | undefined;
+ readonly repository: string;
+ readonly state: PullRequestListState;
+ readonly involvement: PullRequestInvolvement;
+ readonly viewer: string;
+ readonly limit: number;
+ readonly query?: string | undefined;
+ readonly filters?: PullRequestListFilters | undefined;
+ readonly after: string | undefined;
+ readonly collected: ReadonlyArray<GitLabMergeRequestListItem>;
+ readonly states: ReadonlyMap<number, GitLabMergeRequestListState>;
+ readonly cursorAdvance: number;
+ /** Bounds the walk when whole pages fail to decode. */
+ readonly reads: number;
+ }): Effect.Effect<GitLabMergeRequestListBatch, GitLabPullRequestCliError> =>
+ graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "listMergeRequests",
+ ...graphqlListQuery({
+ ...input,
+ first: Math.max(1, Math.min(input.limit - input.collected.length, MAX_PAGE_SIZE)),
+ }),
+ decode: decodeMergeRequestGraphqlListJson,
+ }).pipe(
+ Effect.flatMap((page) => {
+ const collected = [...input.collected, ...page.items];
+ const states = new Map([...input.states, ...page.states]);
+ const cursorAdvance = input.cursorAdvance + page.rawCount;
+ const resumeAfter =
+ page.endCursor !== null && RESUME_AFTER_PATTERN.test(page.endCursor)
+ ? page.endCursor
+ : undefined;
+ if (
+ page.hasNextPage &&
+ resumeAfter !== undefined &&
+ collected.length < input.limit &&
+ input.reads > 1
+ ) {
+ return graphqlListPage({
+ ...input,
+ after: resumeAfter,
+ collected,
+ states,
+ cursorAdvance,
+ reads: input.reads - 1,
+ });
+ }
+ return Effect.succeed({
+ items: collected,
+ truncated: page.hasNextPage,
+ cursorAdvance,
+ ...(resumeAfter === undefined ? {} : { resumeAfter }),
+ listStates: states,
+ });
+ }),
+ );
+
const labelPermission = (input: {
readonly cwd: string;
readonly host?: string | undefined;
@@ -1544,22 +1714,19 @@ export const make = Effect.gen(function* () {
}),
);
- const reviewDecisionsOf = (input: {
+ const listStatesOf = (input: {
readonly cwd: string;
readonly host?: string | undefined;
readonly repository: string;
readonly numbers: ReadonlyArray<number>;
- }): Effect.Effect<
- ReadonlyMap<number, PullRequestReviewDecision | null>,
- GitLabPullRequestCliError
- > =>
+ }): Effect.Effect<ReadonlyMap<number, GitLabMergeRequestListState>, GitLabPullRequestCliError> =>
graphqlRead({
cwd: input.cwd,
host: input.host,
- operation: "getReviewDecisions",
- query: REVIEW_DECISIONS_GRAPHQL_QUERY,
+ operation: "getListStates",
+ query: LIST_STATES_GRAPHQL_QUERY,
variables: { fullPath: input.repository, iids: input.numbers.map(String) },
- decode: decodeReviewDecisionsJson,
+ decode: decodeListStatesJson,
});
const viewerUsername = (input: { readonly cwd: string; readonly host?: string | undefined }) =>
@@ -1588,9 +1755,51 @@ export const make = Effect.gen(function* () {
listMergeRequests: Effect.fn("GitLabPullRequestCli.listMergeRequests")(function (input) {
const perPage = Math.min(input.limit + 1, MAX_PAGE_SIZE);
const page = Math.floor((input.cursor?.delivered ?? 0) / perPage) + 1;
- return listPage({ ...input, page, collected: [], cursorAdvance: 0 });
+ const rest = Effect.suspend(() =>
+ listPage({ ...input, page, collected: [], cursorAdvance: 0 }),
+ );
+ // A cursor's offset means something only to the API that handed it out.
+ const viaGraphql =
+ input.cursor === undefined
+ ? input.graphql === true
+ : input.cursor.resumeAfter !== undefined;
+ if (!viaGraphql) return rest;
+ const graphql = graphqlListPage({
+ ...input,
+ after: input.cursor?.resumeAfter,
+ collected: [],
+ states: new Map(),
+ cursorAdvance: 0,
+ reads: Math.ceil(input.limit / MAX_PAGE_SIZE) + 1,
+ });
+ // GraphQL counts only filtered rows, so its `delivered` is no REST offset once resumed.
+ if (input.cursor !== undefined) return graphql;
+ return graphql.pipe(
+ Effect.catchIf(
+ (cause) =>
+ cause._tag !== "GitLabCliUnavailableError" &&
+ cause._tag !== "GitLabCliAuthenticationError" &&
+ cause._tag !== "GitLabCliRateLimitError",
+ (cause) =>
+ Effect.logWarning("GitLab GraphQL merge request list failed; reading REST instead", {
+ repository: input.repository,
+ reason: cause._tag,
+ }).pipe(Effect.andThen(rest)),
+ ),
+ );
}),
+ supportsGraphqlList: Effect.fn("GitLabPullRequestCli.supportsGraphqlList")((input) =>
+ graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "supportsGraphqlList",
+ query: SERVER_VERSION_GRAPHQL_QUERY,
+ variables: {},
+ decode: decodeGraphqlListSupportJson,
+ }),
+ ),
+
getMergeRequestDetail: Effect.fn("GitLabPullRequestCli.getMergeRequestDetail")(
function* (input) {
const [read, viewerCanEditLabels] = yield* Effect.all(
@@ -1628,12 +1837,12 @@ export const make = Effect.gen(function* () {
},
),
- getReviewDecisions: Effect.fn("GitLabPullRequestCli.getReviewDecisions")(function (input) {
+ getListStates: Effect.fn("GitLabPullRequestCli.getListStates")(function (input) {
const batches: Array<ReadonlyArray<number>> = [];
for (let at = 0; at < input.numbers.length; at += MAX_PAGE_SIZE) {
batches.push(input.numbers.slice(at, at + MAX_PAGE_SIZE));
}
- return Effect.forEach(batches, (numbers) => reviewDecisionsOf({ ...input, numbers }), {
+ return Effect.forEach(batches, (numbers) => listStatesOf({ ...input, numbers }), {
concurrency: 2,
}).pipe(Effect.map((pages) => new Map(pages.flatMap((page) => [...page]))));
}),
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
index 700b8a9c0aa..553f42ff2d9 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
@@ -197,7 +197,7 @@ describe("getChangeRequest base freshness", () => {
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
getMergeRequestDetail: () => Effect.succeed(detail),
- getReviewDecisions: () => Effect.succeed(new Map()),
+ getListStates: () => Effect.succeed(new Map()),
listMergeRequestStats: () => Effect.succeed([]),
}),
@@ -298,7 +298,7 @@ describe("getChangeRequest base freshness", () => {
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
getMergeRequestDetail: () => Effect.succeed(detail),
getProjectMergeCapabilities: () => Effect.die("linked threads skip merge settings"),
- getReviewDecisions: () => Effect.succeed(new Map()),
+ getListStates: () => Effect.succeed(new Map()),
listMergeRequestStats: () =>
Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
}),
@@ -346,7 +346,7 @@ describe("merge request reads", () => {
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
listMergeRequestStats: () => Effect.succeed([]),
- getReviewDecisions: () => Effect.succeed(new Map()),
+ getListStates: () => Effect.succeed(new Map()),
getMergeRequestDetail: (input) =>
Effect.sync(() => {
calls.detail += 1;
@@ -772,19 +772,22 @@ describe("review decisions", () => {
reviewerIds: [],
};
const providerWith = (
- getReviewDecisions: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getReviewDecisions"],
+ getListStates: GitLabPullRequestCli.GitLabPullRequestCli["Service"]["getListStates"],
+ overrides: Partial<GitLabPullRequestCli.GitLabPullRequestCli["Service"]> = {},
) =>
make.pipe(
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
+ supportsGraphqlList: () => Effect.succeed(false),
listMergeRequests: () =>
Effect.succeed({
items: [item, { ...item, number: 8 }],
truncated: false,
cursorAdvance: 2,
}),
+ ...overrides,
getMergeRequestDetail: () => Effect.succeed(detail),
- getReviewDecisions,
+ getListStates,
listMergeRequestStats: () =>
Effect.succeed([{ repository: "acme/web", number: 7, additions: 40, deletions: 2 }]),
}),
@@ -800,26 +803,97 @@ describe("review decisions", () => {
limit: 2,
};
- it.effect("puts GitLab's approval state on listed and summarized merge requests", () =>
- Effect.gen(function* () {
- const provider = yield* providerWith((input) => {
- expect(input.host).toBe(reference.host);
- return Effect.succeed(
- new Map([
- [7, "approved" as const],
- [8, null],
- ]),
- );
- });
- const listed = yield* provider.listChangeRequests(listing);
- assert.isDefined(provider.getChangeRequestSummary);
- const summary = yield* provider.getChangeRequestSummary(reference);
+ it.effect(
+ "puts GitLab's approval and pipeline state on listed and summarized merge requests",
+ () =>
+ Effect.gen(function* () {
+ const provider = yield* providerWith((input) => {
+ expect(input.host).toBe(reference.host);
+ return Effect.succeed(
+ new Map([
+ [7, { reviewDecision: "approved" as const, checksState: "failing" as const }],
+ [8, { reviewDecision: null, checksState: null }],
+ ]),
+ );
+ });
+ const listed = yield* provider.listChangeRequests(listing);
+ assert.isDefined(provider.getChangeRequestSummary);
+ const summary = yield* provider.getChangeRequestSummary(reference);
+
+ expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual([
+ "approved",
+ null,
+ ]);
+ expect(listed.items.map(({ checksState }) => checksState)).toEqual(["failing", null]);
+ expect(summary.reviewDecision).toBe("approved");
+ expect(summary.checksState).toBe("failing");
+ expect(summary.additions).toBe(40);
+ expect(summary.deletions).toBe(2);
+ }),
+ );
- expect(listed.items.map(({ reviewDecision }) => reviewDecision)).toEqual(["approved", null]);
- expect(summary.reviewDecision).toBe("approved");
- expect(summary.additions).toBe(40);
- expect(summary.deletions).toBe(2);
- }),
+ it.effect(
+ "lists through GraphQL where the host takes it, using the states that read carried",
+ () =>
+ Effect.gen(function* () {
+ const graphqlFlags: Array<boolean | undefined> = [];
+ let versionReads = 0;
+ const providerReading = (
+ supportsGraphqlList: Effect.Effect<
+ boolean,
+ GitLabPullRequestCli.GitLabPullRequestCliError
+ >,
+ ) =>
+ providerWith(() => Effect.die("a GraphQL page carries its own states"), {
+ supportsGraphqlList: () => {
+ versionReads += 1;
+ return supportsGraphqlList;
+ },
+ listMergeRequests: (input) => {
+ graphqlFlags.push(input.graphql);
+ return Effect.succeed({
+ items: [item],
+ truncated: true,
+ cursorAdvance: 1,
+ resumeAfter: "eyJpZCI6IjcifQ",
+ listStates: new Map([
+ [7, { reviewDecision: "changes-requested" as const, checksState: null }],
+ ]),
+ });
+ },
+ });
+ const listedWith = (
+ supportsGraphqlList: Effect.Effect<
+ boolean,
+ GitLabPullRequestCli.GitLabPullRequestCliError
+ >,
+ ) =>
+ providerReading(supportsGraphqlList).pipe(
+ Effect.flatMap((provider) => provider.listChangeRequests(listing)),
+ );
+
+ const listed = yield* listedWith(Effect.succeed(true));
+ expect(listed).toMatchObject({ resumeAfter: "eyJpZCI6IjcifQ", truncated: true });
+ expect(listed).not.toHaveProperty("listStates");
+ expect(listed.items[0]?.reviewDecision).toBe("changes-requested");
+
+ // An unreadable version leaves the list on REST rather than failing it, and stays known.
+ const unreadable = yield* providerReading(
+ Effect.fail(
+ new GitLabPullRequestCli.GitLabMergeRequestReadError({
+ command: "glab",
+ cwd: "/w",
+ operation: "supportsGraphqlList",
+ cause: null,
+ }),
+ ),
+ );
+ versionReads = 0;
+ yield* unreadable.listChangeRequests(listing);
+ yield* unreadable.listChangeRequests(listing);
+ expect(graphqlFlags).toEqual([true, false, false]);
+ expect(versionReads).toBe(1);
+ }),
);
it.effect.each([
@@ -828,7 +902,7 @@ describe("review decisions", () => {
error: new GitLabPullRequestCli.GitLabMergeRequestReadError({
command: "glab",
cwd: "/w",
- operation: "getReviewDecisions",
+ operation: "getListStates",
cause: null,
}),
},
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
index 9d2e4a1fc33..5fb23c8750d 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
@@ -8,11 +8,11 @@ import type {
PullRequestActor,
PullRequestCapabilities,
PullRequestReaction,
- PullRequestReviewDecision,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
+import type { GitLabMergeRequestListState } from "./gitLabMergeRequestJson.ts";
import {
PullRequestProviderError,
type PullRequestProviderFailure,
@@ -94,6 +94,8 @@ const MERGE_REQUEST_DETAIL_TTL = Duration.minutes(1);
/** A project's merge methods change in its settings, which nobody does between page views. */
const PROJECT_MERGE_CAPABILITIES_TTL = Duration.minutes(15);
const READ_CACHE_CAPACITY = 256;
+/** A host's GitLab version only changes on upgrade. */
+const GRAPHQL_LIST_SUPPORT_TTL = Duration.hours(1);
function gitLabProviderFailure(
error: GitLabPullRequestCli.GitLabPullRequestCliError,
@@ -120,6 +122,25 @@ export const make = Effect.gen(function* () {
timeToLive: (exit) => (Exit.isSuccess(exit) ? MERGE_REQUEST_DETAIL_TTL : Duration.zero),
},
);
+ const graphqlListSupport = yield* Cache.makeWith(
+ (key: string) => {
+ const [cwd, host] = JSON.parse(key) as [string, string | undefined];
+ // A host whose version read fails keeps failing it; remember REST rather than ask each poll.
+ return cli.supportsGraphqlList({ cwd, host }).pipe(
+ Effect.catchIf(
+ (cause) =>
+ cause._tag !== "GitLabCliUnavailableError" &&
+ cause._tag !== "GitLabCliAuthenticationError" &&
+ cause._tag !== "GitLabCliRateLimitError",
+ () => Effect.succeed(false),
+ ),
+ );
+ },
+ {
+ capacity: READ_CACHE_CAPACITY,
+ timeToLive: (exit) => (Exit.isSuccess(exit) ? GRAPHQL_LIST_SUPPORT_TTL : Duration.zero),
+ },
+ );
const projectMergeCapabilities = yield* Cache.makeWith(
(key: string) => {
const [cwd, repository, host] = JSON.parse(key) as [string, string, string];
@@ -190,14 +211,14 @@ export const make = Effect.gen(function* () {
}),
);
- // The rows were already read, so even a rate limit only leaves their decision unknown.
- const reviewDecisions = (input: Parameters<typeof cli.getReviewDecisions>[0]) =>
- cli.getReviewDecisions(input).pipe(
+ // The rows were already read, so even a rate limit only leaves their states unknown.
+ const listStates = (input: Parameters<typeof cli.getListStates>[0]) =>
+ cli.getListStates(input).pipe(
Effect.catch((error) =>
- Effect.logWarning("GitLab merge request approval read failed", {
+ Effect.logWarning("GitLab merge request approval and pipeline read failed", {
repository: input.repository,
reason: error._tag,
- }).pipe(Effect.as<ReadonlyMap<number, PullRequestReviewDecision | null>>(new Map())),
+ }).pipe(Effect.as<ReadonlyMap<number, GitLabMergeRequestListState>>(new Map())),
),
);
@@ -236,36 +257,43 @@ export const make = Effect.gen(function* () {
getViewer: (input) => cli.getViewerUsername(input).pipe(Effect.mapError(fail("getViewer"))),
listChangeRequests: (input) =>
- cli
- .listMergeRequests({
- cwd: input.cwd,
- host: input.host,
- repository: input.repository,
- state: input.state,
- involvement: input.involvement,
- viewer: input.viewer,
- limit: input.limit,
- query: input.query,
- cursor: input.cursor,
- filters: input.filters,
- })
- .pipe(
- Effect.flatMap((batch) =>
- reviewDecisions({
- cwd: input.cwd,
- host: input.host,
- repository: input.repository,
- numbers: batch.items.map((item) => item.number),
- }).pipe(
- Effect.map((decisions) => ({
- ...batch,
- items: batch.items.map((item) => withReviewDecision(item, decisions)),
- continues: true,
- })),
- ),
+ Cache.get(graphqlListSupport, JSON.stringify([input.cwd, input.host])).pipe(
+ // Without a known version the REST list still answers, only with fewer filters.
+ Effect.orElseSucceed(() => false),
+ Effect.flatMap((graphql) =>
+ cli.listMergeRequests({
+ cwd: input.cwd,
+ host: input.host,
+ repository: input.repository,
+ state: input.state,
+ involvement: input.involvement,
+ viewer: input.viewer,
+ limit: input.limit,
+ query: input.query,
+ cursor: input.cursor,
+ filters: input.filters,
+ graphql,
+ }),
+ ),
+ Effect.flatMap(({ listStates: carried, ...batch }) =>
+ (carried === undefined
+ ? listStates({
+ cwd: input.cwd,
+ host: input.host,
+ repository: input.repository,
+ numbers: batch.items.map((item) => item.number),
+ })
+ : Effect.succeed(carried)
+ ).pipe(
+ Effect.map((states) => ({
+ ...batch,
+ items: batch.items.map((item) => withListState(item, states)),
+ continues: true,
+ })),
),
- Effect.mapError(fail("listChangeRequests")),
),
+ Effect.mapError(fail("listChangeRequests")),
+ ),
getFileStats: (input) =>
cli.getMergeRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
@@ -287,7 +315,7 @@ export const make = Effect.gen(function* () {
Effect.all(
[
mergeRequestWithStats(input),
- reviewDecisions({
+ listStates({
cwd: input.cwd,
host: input.host,
repository: input.repository,
@@ -296,7 +324,7 @@ export const make = Effect.gen(function* () {
],
{ concurrency: 2 },
).pipe(
- Effect.map(([mergeRequest, decisions]) => withReviewDecision(mergeRequest, decisions)),
+ Effect.map(([mergeRequest, states]) => withListState(mergeRequest, states)),
Effect.mapError(fail("getChangeRequestSummary")),
),
@@ -584,10 +612,10 @@ export const make = Effect.gen(function* () {
return provider;
});
-function withReviewDecision<Item extends { readonly number: number }>(
+function withListState<Item extends { readonly number: number }>(
item: Item,
- decisions: ReadonlyMap<number, PullRequestReviewDecision | null>,
-): Item & { readonly reviewDecision?: PullRequestReviewDecision | null } {
- const reviewDecision = decisions.get(item.number);
- return reviewDecision === undefined ? item : { ...item, reviewDecision };
+ states: ReadonlyMap<number, GitLabMergeRequestListState>,
+): Item & Partial<GitLabMergeRequestListState> {
+ const state = states.get(item.number);
+ return state === undefined ? item : { ...item, ...state };
}
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
index 2b3ff84330c..1ff3de91626 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts
@@ -5,6 +5,8 @@ import {
decodeAwardEmojiJson,
decodeRepositoryBlobsJson,
decodeCommitsJson,
+ decodeGraphqlListSupportJson,
+ decodeMergeRequestGraphqlListJson,
decodeMergeMessagesJson,
decodeMergeRequestDetailJson,
decodeMergeRequestDiffsJson,
@@ -13,7 +15,7 @@ import {
decodeMergeRequestStatsJson,
decodeNotesJson,
decodeOwnAwardIdJson,
- decodeReviewDecisionsJson,
+ decodeListStatesJson,
decodeTriggerJobChecksJson,
} from "./gitLabMergeRequestJson.ts";
@@ -708,10 +710,10 @@ describe("decodeRepositoryBlobsJson", () => {
});
});
-describe("decodeReviewDecisionsJson", () => {
- const decisionsOf = (enterprise: boolean | null, nodes: ReadonlyArray<unknown>) =>
+describe("decodeListStatesJson", () => {
+ const statesOf = (enterprise: boolean | null, nodes: ReadonlyArray<unknown>) =>
expectSuccess(
- decodeReviewDecisionsJson(
+ decodeListStatesJson(
JSON.stringify({
data: {
metadata: enterprise === null ? null : { enterprise },
@@ -723,6 +725,9 @@ describe("decodeReviewDecisionsJson", () => {
const approvedBy = (...usernames: ReadonlyArray<string>) => ({
nodes: usernames.map((username) => ({ username })),
});
+ const reviewers = (...reviewStates: ReadonlyArray<string>) => ({
+ nodes: reviewStates.map((reviewState) => ({ mergeRequestInteraction: { reviewState } })),
+ });
it.each([
{
@@ -761,25 +766,89 @@ describe("decodeReviewDecisionsJson", () => {
approval: { approved: false, approvedBy: approvedBy() },
decision: null,
},
+ {
+ reading: "a reviewer requesting changes after another approved",
+ enterprise: true,
+ approval: {
+ approved: true,
+ approvedBy: approvedBy("julius"),
+ reviewers: reviewers("APPROVED", "REQUESTED_CHANGES"),
+ },
+ decision: "changes-requested",
+ },
+ {
+ reading: "a Community Edition reviewer requesting changes",
+ enterprise: false,
+ approval: {
+ approved: false,
+ approvedBy: approvedBy(),
+ reviewers: reviewers("REQUESTED_CHANGES"),
+ },
+ decision: "changes-requested",
+ },
+ {
+ reading: "reviewers who have not asked for changes",
+ enterprise: false,
+ approval: {
+ approved: true,
+ approvedBy: approvedBy("julius"),
+ reviewers: reviewers("UNREVIEWED", "REVIEWED"),
+ },
+ decision: "approved",
+ },
])("reads $reading as $decision", ({ enterprise, approval, decision }) => {
- expect([...decisionsOf(enterprise, [{ iid: "7", ...approval }])]).toEqual([[7, decision]]);
+ expect([...statesOf(enterprise, [{ iid: "7", ...approval }])]).toEqual([
+ [7, { reviewDecision: decision, checksState: null }],
+ ]);
});
+ it.each([
+ { pipeline: { status: "SUCCESS" }, checksState: "passing" },
+ { pipeline: { status: "FAILED" }, checksState: "failing" },
+ { pipeline: { status: "CANCELED" }, checksState: "failing" },
+ { pipeline: { status: "RUNNING" }, checksState: "pending" },
+ { pipeline: { status: "WAITING_FOR_RESOURCE" }, checksState: "pending" },
+ { pipeline: { status: "MANUAL" }, checksState: null },
+ { pipeline: { status: "SKIPPED" }, checksState: null },
+ { pipeline: null, checksState: null },
+ ])(
+ "reads a $pipeline.status head pipeline as $checksState checks",
+ ({ pipeline, checksState }) => {
+ expect([
+ ...statesOf(false, [
+ { iid: "7", approved: false, approvedBy: approvedBy(), headPipeline: pipeline },
+ ]),
+ ]).toEqual([[7, { reviewDecision: null, checksState }]]);
+ },
+ );
+
it("leaves out a merge request it cannot key, and a project the reader cannot see", () => {
- expect([...decisionsOf(true, [null, { iid: "x", approved: true }])]).toEqual([]);
- expect([
- ...decisionsOf(null, [{ iid: "7", approved: false, approvedBy: approvedBy() }]),
- ]).toEqual([]);
- expect([
- ...decisionsOf(true, [
- { iid: "7", approved: null, approvedBy: approvedBy("julius") },
- { iid: "8", approved: true, approvedBy: null },
- ]),
- ]).toEqual([]);
+ expect([...statesOf(true, [null, { iid: "x", approved: true }])]).toEqual([]);
expect(
- expectSuccess(decodeReviewDecisionsJson(JSON.stringify({ data: { project: null } }))),
+ expectSuccess(decodeListStatesJson(JSON.stringify({ data: { project: null } }))),
).toEqual(new Map());
});
+
+ it("keeps the checks of a merge request whose approval it cannot judge", () => {
+ expect([
+ ...statesOf(null, [
+ {
+ iid: "7",
+ approved: false,
+ approvedBy: approvedBy(),
+ headPipeline: { status: "FAILED" },
+ },
+ ]),
+ ...statesOf(true, [
+ { iid: "8", approved: null, approvedBy: approvedBy("julius") },
+ { iid: "9", approved: true, approvedBy: null },
+ ]),
+ ]).toEqual([
+ [7, { checksState: "failing" }],
+ [8, { checksState: null }],
+ [9, { checksState: null }],
+ ]);
+ });
});
describe("decodeMergeRequestStatsJson", () => {
@@ -838,6 +907,93 @@ describe("decodeMergeRequestStatsJson", () => {
});
});
+describe("decodeMergeRequestGraphqlListJson", () => {
+ it("reads a row and its review state in one page, counting rows it cannot read", () => {
+ const page = expectSuccess(
+ decodeMergeRequestGraphqlListJson(
+ JSON.stringify({
+ data: {
+ metadata: { enterprise: false },
+ project: {
+ mergeRequests: {
+ pageInfo: { hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" },
+ nodes: [
+ {
+ iid: "7",
+ title: "Add the merge requests page",
+ webUrl: "https://gitlab.com/acme/web/-/merge_requests/7",
+ state: "opened",
+ draft: true,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ sourceBranch: "feat/page",
+ targetBranch: "main",
+ conflicts: true,
+ mergeStatusEnum: "CHECKING",
+ author: { username: "bilal", name: "Bilal", avatarUrl: null },
+ labels: { nodes: [{ title: "bug" }] },
+ approved: false,
+ approvedBy: { nodes: [] },
+ reviewers: {
+ nodes: [
+ {
+ username: "julius",
+ mergeRequestInteraction: { reviewState: "REQUESTED_CHANGES" },
+ },
+ ],
+ },
+ headPipeline: { status: "FAILED" },
+ },
+ { iid: "8" },
+ ],
+ },
+ },
+ },
+ }),
+ ),
+ );
+
+ expect(page.items).toEqual([
+ expect.objectContaining({
+ number: 7,
+ state: "open",
+ isDraft: true,
+ mergeability: "conflicting",
+ reviewRequestLogins: ["julius"],
+ labels: [expect.objectContaining({ name: "bug" })],
+ }),
+ ]);
+ expect([...page.states]).toEqual([
+ [7, { reviewDecision: "changes-requested", checksState: "failing" }],
+ ]);
+ expect(page).toMatchObject({ rawCount: 2, hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" });
+ });
+ it("fails on a project the reader cannot see, rather than reading it as empty", () => {
+ expect(
+ Result.isFailure(
+ decodeMergeRequestGraphqlListJson(
+ JSON.stringify({ data: { metadata: { enterprise: true }, project: null } }),
+ ),
+ ),
+ ).toBe(true);
+ });
+});
+
+describe("decodeGraphqlListSupportJson", () => {
+ it.each([
+ { version: "17.8.4", supported: false },
+ { version: "17.9.0", supported: true },
+ { version: "19.6.0-pre", supported: true },
+ { version: null, supported: false },
+ ])("reads GitLab $version as supported: $supported", ({ version, supported }) => {
+ expect(
+ expectSuccess(
+ decodeGraphqlListSupportJson(JSON.stringify({ data: { metadata: { version } } })),
+ ),
+ ).toBe(supported);
+ });
+});
+
describe("decodeMergeMessagesJson", () => {
it("fails a partial response instead of reading errored fields as absent templates", () => {
const decoded = decodeMergeMessagesJson(
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
index 1796778aa49..24ad0f02a43 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
@@ -7,6 +7,7 @@ import type {
PullRequestActor,
PullRequestCheck,
PullRequestCheckStatus,
+ PullRequestChecksState,
PullRequestComment,
PullRequestCommit,
PullRequestLabel,
@@ -222,7 +223,9 @@ function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefine
: { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
}
-function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullRequestState {
+function toState(
+ raw: Pick<Schema.Schema.Type<typeof RawMergeRequestSchema>, "state" | "merged_at">,
+): PullRequestState {
if (trimmed(raw.merged_at) !== null) return "merged";
switch (raw.state?.trim().toLowerCase()) {
case "merged":
@@ -235,7 +238,7 @@ function toState(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): PullReq
}
function toMergeability(
- raw: Schema.Schema.Type<typeof RawMergeRequestSchema>,
+ raw: Pick<Schema.Schema.Type<typeof RawMergeRequestSchema>, "has_conflicts" | "merge_status">,
): PullRequestMergeability {
if (raw.has_conflicts === true) return "conflicting";
switch (raw.merge_status?.trim().toLowerCase()) {
@@ -1213,41 +1216,71 @@ export function decodeMergeMessagesJson(
});
}
-export const REVIEW_DECISIONS_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) {
+/** What a listed merge request needs beyond REST: its approval, reviewer and pipeline state. */
+const LIST_STATE_GRAPHQL_FIELDS = `iid approved approvedBy(first: 1) { nodes { username } }
+ reviewers(first: 20) { nodes { username mergeRequestInteraction { reviewState } } }
+ headPipeline { status }`;
+
+export const LIST_STATES_GRAPHQL_QUERY = `query($fullPath: ID!, $iids: [String!]) {
metadata { enterprise }
project(fullPath: $fullPath) {
mergeRequests(iids: $iids, first: 100) {
- nodes { iid approved approvedBy(first: 1) { nodes { username } } }
+ nodes { ${LIST_STATE_GRAPHQL_FIELDS} }
}
}
}`;
-const RawReviewDecisionsSchema = Schema.Struct({
- data: Schema.Struct({
- metadata: Schema.optional(
- Schema.NullOr(Schema.Struct({ enterprise: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
+const RawMetadataSchema = Schema.optional(
+ Schema.NullOr(Schema.Struct({ enterprise: Schema.optional(Schema.NullOr(Schema.Boolean)) })),
+);
+
+const RawListStateFields = {
+ iid: Schema.String,
+ approved: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ approvedBy: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
+ }),
),
- project: Schema.NullOr(
+ ),
+ reviewers: Schema.optional(
+ Schema.NullOr(
Schema.Struct({
- mergeRequests: Schema.optional(
+ nodes: Schema.optional(
Schema.NullOr(
- Schema.Struct({
- nodes: Schema.Array(
- Schema.NullOr(
- Schema.Struct({
- iid: Schema.String,
- approved: Schema.optional(Schema.NullOr(Schema.Boolean)),
- approvedBy: Schema.optional(
- Schema.NullOr(
- Schema.Struct({
- nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
- }),
- ),
+ Schema.Array(
+ Schema.NullOr(
+ Schema.Struct({
+ username: Schema.optional(Schema.NullOr(Schema.String)),
+ mergeRequestInteraction: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({ reviewState: Schema.optional(Schema.NullOr(Schema.String)) }),
),
- }),
- ),
+ ),
+ }),
),
- }),
+ ),
+ ),
+ ),
+ }),
+ ),
+ ),
+ headPipeline: Schema.optional(
+ Schema.NullOr(Schema.Struct({ status: Schema.optional(Schema.NullOr(Schema.String)) })),
+ ),
+};
+
+const RawListStateNodeSchema = Schema.Struct(RawListStateFields);
+
+const RawListStatesSchema = Schema.Struct({
+ data: Schema.Struct({
+ metadata: RawMetadataSchema,
+ project: Schema.NullOr(
+ Schema.Struct({
+ mergeRequests: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({ nodes: Schema.Array(Schema.NullOr(RawListStateNodeSchema)) }),
),
),
}),
@@ -1255,43 +1288,234 @@ const RawReviewDecisionsSchema = Schema.Struct({
}),
});
-const decodeReviewDecisions = decodeJsonResult(RawReviewDecisionsSchema);
+const decodeListStates = decodeJsonResult(RawListStatesSchema);
+
+export interface GitLabMergeRequestListState {
+ /** Absent when the approval state can't be judged. */
+ readonly reviewDecision?: PullRequestReviewDecision | null;
+ readonly checksState: PullRequestChecksState | null;
+}
+
+function toChecksState(pipelineStatus: string | null | undefined): PullRequestChecksState | null {
+ if (pipelineStatus == null) return null;
+ switch (toPipelineStatus(pipelineStatus)) {
+ case "success":
+ return "passing";
+ case "failure":
+ case "cancelled":
+ return "failing";
+ case "pending":
+ return "pending";
+ default:
+ return null;
+ }
+}
/**
* Only Enterprise Edition holds `approved` to the project's approval rules, so an unapproved
* merge request there still needs review even when someone, such as a bot, approved it.
* Community Edition reports `approved` once anyone approves and requires no review.
+ * A reviewer asking for changes outranks both, as it does on GitHub.
*/
-export function decodeReviewDecisionsJson(
+function toListState(
+ node: typeof RawListStateNodeSchema.Type,
+ enterprise: boolean | null | undefined,
+): GitLabMergeRequestListState {
+ const checksState = toChecksState(node.headPipeline?.status);
+ if (
+ node.reviewers?.nodes?.some(
+ (reviewer) => reviewer?.mergeRequestInteraction?.reviewState === "REQUESTED_CHANGES",
+ )
+ ) {
+ return { reviewDecision: "changes-requested", checksState };
+ }
+ const approvals = node.approvedBy?.nodes?.length;
+ if (
+ node.approved == null ||
+ approvals === undefined ||
+ (node.approved === false && approvals === 0 && enterprise == null)
+ ) {
+ return { checksState };
+ }
+ return {
+ reviewDecision:
+ node.approved === false && (enterprise || approvals > 0)
+ ? "review-required"
+ : approvals > 0
+ ? "approved"
+ : null,
+ checksState,
+ };
+}
+
+export function decodeListStatesJson(
raw: string,
-): Result.Result<ReadonlyMap<number, PullRequestReviewDecision | null>, DecodeFailure> {
- const decoded = decodeReviewDecisions(raw);
+): Result.Result<ReadonlyMap<number, GitLabMergeRequestListState>, DecodeFailure> {
+ const decoded = decodeListStates(raw);
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const enterprise = decoded.success.data.metadata?.enterprise;
- const decisions = new Map<number, PullRequestReviewDecision | null>();
+ const states = new Map<number, GitLabMergeRequestListState>();
for (const node of decoded.success.data.project?.mergeRequests?.nodes ?? []) {
const number = Number(node?.iid);
- if (
- node === null ||
- !Number.isSafeInteger(number) ||
- node.approved == null ||
- node.approvedBy?.nodes == null
- )
- continue;
- const approvals = node.approvedBy.nodes.length;
- if (node.approved === false && approvals === 0 && enterprise == null) continue;
- decisions.set(
+ if (node === null || !Number.isSafeInteger(number)) continue;
+ states.set(number, toListState(node, enterprise));
+ }
+ return Result.succeed(states);
+}
+
+/** The fields a listed merge request needs, so one GraphQL read stands in for REST and states. */
+export const LIST_ITEM_GRAPHQL_FIELDS = `${LIST_STATE_GRAPHQL_FIELDS}
+ title webUrl state draft createdAt updatedAt mergedAt sourceBranch targetBranch
+ conflicts mergeStatusEnum author { username name avatarUrl } labels(first: 100) { nodes { title } }`;
+
+const RawGraphqlListNodeSchema = Schema.Struct({
+ ...RawListStateFields,
+ title: Schema.String,
+ webUrl: Schema.String,
+ state: Schema.optional(Schema.NullOr(Schema.String)),
+ draft: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ createdAt: Schema.String,
+ updatedAt: Schema.String,
+ mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
+ sourceBranch: Schema.String,
+ targetBranch: Schema.String,
+ conflicts: Schema.optional(Schema.NullOr(Schema.Boolean)),
+ mergeStatusEnum: Schema.optional(Schema.NullOr(Schema.String)),
+ author: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ username: Schema.optional(Schema.NullOr(Schema.String)),
+ name: Schema.optional(Schema.NullOr(Schema.String)),
+ avatarUrl: Schema.optional(Schema.NullOr(Schema.String)),
+ }),
+ ),
+ ),
+ labels: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ nodes: Schema.optional(
+ Schema.NullOr(Schema.Array(Schema.NullOr(Schema.Struct({ title: Schema.String })))),
+ ),
+ }),
+ ),
+ ),
+});
+
+// GitLab answers `project: null` for a project the reader cannot see, which REST reports as an error.
+const RawGraphqlListSchema = Schema.Struct({
+ data: Schema.Struct({
+ metadata: RawMetadataSchema,
+ project: Schema.Struct({
+ mergeRequests: Schema.Struct({
+ pageInfo: Schema.Struct({
+ hasNextPage: Schema.Boolean,
+ endCursor: Schema.optional(Schema.NullOr(Schema.String)),
+ }),
+ nodes: Schema.Array(Schema.Unknown),
+ }),
+ }),
+ }),
+});
+
+const decodeGraphqlList = decodeJsonResult(RawGraphqlListSchema);
+const decodeGraphqlListNode = Schema.decodeUnknownExit(RawGraphqlListNodeSchema);
+
+export interface GitLabMergeRequestGraphqlPage {
+ readonly items: ReadonlyArray<GitLabMergeRequestListItem>;
+ readonly states: ReadonlyMap<number, GitLabMergeRequestListState>;
+ /** Count before decoding, so a page of rows that fail to decode still moves on. */
+ readonly rawCount: number;
+ readonly hasNextPage: boolean;
+ readonly endCursor: string | null;
+}
+
+export function decodeMergeRequestGraphqlListJson(
+ raw: string,
+): Result.Result<GitLabMergeRequestGraphqlPage, DecodeFailure> {
+ const decoded = decodeGraphqlList(raw);
+ if (!Result.isSuccess(decoded)) {
+ return Result.fail(decoded.failure);
+ }
+ const page = decoded.success.data.project.mergeRequests;
+ const enterprise = decoded.success.data.metadata?.enterprise;
+ const items: GitLabMergeRequestListItem[] = [];
+ const states = new Map<number, GitLabMergeRequestListState>();
+ for (const entry of page.nodes) {
+ const exit = decodeGraphqlListNode(entry);
+ if (!Exit.isSuccess(exit)) continue;
+ const node = exit.value;
+ const number = Number(node.iid);
+ if (!Number.isSafeInteger(number)) continue;
+ items.push({
number,
- node.approved === false && (enterprise || approvals > 0)
- ? "review-required"
- : approvals > 0
- ? "approved"
- : null,
- );
+ title: node.title,
+ url: node.webUrl,
+ author: toActor(
+ node.author == null
+ ? null
+ : {
+ username: node.author.username ?? "",
+ name: node.author.name,
+ avatar_url: node.author.avatarUrl,
+ },
+ ),
+ headBranch: node.sourceBranch,
+ baseBranch: node.targetBranch,
+ state: toState({ state: node.state, merged_at: node.mergedAt }),
+ isDraft: node.draft ?? false,
+ mergeability: toMergeability({
+ has_conflicts: node.conflicts,
+ merge_status: node.mergeStatusEnum,
+ }),
+ additions: 0,
+ deletions: 0,
+ createdAt: node.createdAt,
+ updatedAt: node.updatedAt,
+ reviewRequestLogins: (node.reviewers?.nodes ?? []).flatMap((reviewer) => {
+ const login = trimmed(reviewer?.username);
+ return login === null ? [] : [login];
+ }),
+ labels: toLabels((node.labels?.nodes ?? []).flatMap((label) => (label ? [label.title] : []))),
+ });
+ states.set(number, toListState(node, enterprise));
+ }
+ return Result.succeed({
+ items,
+ states,
+ rawCount: page.nodes.length,
+ hasNextPage: page.pageInfo.hasNextPage,
+ endCursor: trimmed(page.pageInfo.endCursor),
+ });
+}
+
+export const SERVER_VERSION_GRAPHQL_QUERY = "{ metadata { version } }";
+
+const decodeServerVersion = decodeJsonResult(
+ Schema.Struct({
+ data: Schema.Struct({
+ metadata: Schema.optional(
+ Schema.NullOr(Schema.Struct({ version: Schema.optional(Schema.NullOr(Schema.String)) })),
+ ),
+ }),
+ }),
+);
+
+/**
+ * Whether the GraphQL merge request list takes every filter the REST list does: `search` came
+ * last, in 17.9. An instance that hides its version keeps REST.
+ */
+export function decodeGraphqlListSupportJson(raw: string): Result.Result<boolean, DecodeFailure> {
+ const decoded = decodeServerVersion(raw);
+ if (!Result.isSuccess(decoded)) {
+ return Result.fail(decoded.failure);
}
- return Result.succeed(decisions);
+ const match = /^(\d+)\.(\d+)/u.exec(decoded.success.data.metadata?.version?.trim() ?? "");
+ if (match === null) return Result.succeed(false);
+ const major = Number(match[1]);
+ const minor = Number(match[2]);
+ return Result.succeed(major > 17 || (major === 17 && minor >= 9));
}
/**