Skip to content

Commit c501cca

Browse files
fix(server): PR watch waits for queued GitHub workflow runs (pingdotgg#34624)
1 parent c8ddb22 commit c501cca

5 files changed

Lines changed: 155 additions & 7 deletions

File tree

‎packages/source-control-github/src/server/GitHubPullRequestApi.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2756,6 +2756,38 @@ layer("GitHubPullRequestApi.layer", (it) => {
27562756
}),
27572757
);
27582758

2759+
it.effect("lists only the head's workflow runs that have not finished", () =>
2760+
Effect.gen(function* () {
2761+
mockedExecute.mockImplementation(() =>
2762+
Effect.succeed(
2763+
output(
2764+
encodeJson({
2765+
workflow_runs: ["queued", "in_progress", "completed", "action_required", null].map(
2766+
(status, index) => ({ id: index, name: `${status}`, html_url: null, status }),
2767+
),
2768+
}),
2769+
),
2770+
),
2771+
);
2772+
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2773+
2774+
const runs = yield* cli.listUnfinishedWorkflowRuns({
2775+
cwd: "/w",
2776+
repository: "acme/web",
2777+
host: "github.com",
2778+
headSha: "abc123",
2779+
});
2780+
2781+
expect(restCallsTo("actions/runs?")[0]?.path).toBe(
2782+
"repos/acme/web/actions/runs?head_sha=abc123&per_page=100",
2783+
);
2784+
expect(runs).toEqual([
2785+
{ id: 0, name: "queued", url: null },
2786+
{ id: 1, name: "in_progress", url: null },
2787+
]);
2788+
}),
2789+
);
2790+
27592791
it.effect("refuses workflow approval when one head belongs to several pull requests", () =>
27602792
Effect.gen(function* () {
27612793
workflowApprovalRoutes(() => crossRepositoryDetail(), heads([7, 8]), workflowRuns([]));

‎packages/source-control-github/src/server/GitHubPullRequestApi.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ import {
6969
decodeCommitFilesJson,
7070
pullRequestChecksFromContexts,
7171
decodeWorkflowRunsJson,
72+
decodeUnfinishedWorkflowRunsJson,
7273
type GitHubPullRequestCore,
7374
type GitHubPullRequestFileStat,
7475
type GitHubPullRequestWatchFingerprint,
@@ -549,6 +550,14 @@ export class GitHubPullRequestApi extends Context.Service<
549550
readonly isCrossRepository: true;
550551
}) => Effect.Effect<ReadonlyArray<GitHubWorkflowRunApproval>, GitHubPullRequestApiError>;
551552

553+
/** The head's workflow runs that have not finished, the latest 100. */
554+
readonly listUnfinishedWorkflowRuns: (input: {
555+
readonly cwd: string;
556+
readonly repository: string;
557+
readonly host: string;
558+
readonly headSha: string;
559+
}) => Effect.Effect<ReadonlyArray<GitHubWorkflowRunApproval>, GitHubPullRequestApiError>;
560+
552561
readonly getPullRequestStack: (input: {
553562
readonly cwd: string;
554563
readonly includeDetails?: boolean;
@@ -2076,6 +2085,19 @@ export const make = Effect.gen(function* () {
20762085
},
20772086
),
20782087
listWorkflowRunsRequiringApproval,
2088+
listUnfinishedWorkflowRuns: Effect.fn("GitHubPullRequestApi.listUnfinishedWorkflowRuns")(
2089+
function (input) {
2090+
const { owner, name } = parseRepositorySelector(input.repository);
2091+
// Read with every pull request detail, so revalidate it.
2092+
return revalidatedRestRead({
2093+
cwd: input.cwd,
2094+
host: input.host,
2095+
operation: "listUnfinishedWorkflowRuns",
2096+
path: `repos/${owner}/${name}/actions/runs?head_sha=${encodeURIComponent(input.headSha)}&per_page=100`,
2097+
decode: decodeUnfinishedWorkflowRunsJson,
2098+
});
2099+
},
2100+
),
20792101

20802102
getPullRequestStack: Effect.fn("GitHubPullRequestApi.getPullRequestStack")(function (input) {
20812103
const { owner, name } = parseRepositorySelector(input.repository);

‎packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,7 @@ describe("gitHubViewerPermissions", () => {
415415
comments: [],
416416
commits: [],
417417
}),
418+
listUnfinishedWorkflowRuns: () => Effect.succeed([]),
418419
listWorkflowRunsRequiringApproval: () =>
419420
Effect.succeed([
420421
{
@@ -470,7 +471,17 @@ const openDetail = {
470471
commits: [],
471472
};
472473

473-
it.effect("does not classify same-repository gates as fork workflow approvals", () =>
474+
const sameRepositoryChecks = [
475+
{ name: "CodeRabbit", status: "skipped" as const, description: null, url: null },
476+
{
477+
name: "lint",
478+
status: "pending" as const,
479+
description: null,
480+
url: "https://github.com/acme/web/actions/runs/201/job/1",
481+
},
482+
];
483+
484+
it.effect("adds unstarted same-repository workflow runs as pending, not as approvals", () =>
474485
Effect.gen(function* () {
475486
const provider = yield* make;
476487
const detail = yield* provider.getChangeRequest({
@@ -481,12 +492,27 @@ it.effect("does not classify same-repository gates as fork workflow approvals",
481492
});
482493

483494
expect(detail.workflowApprovalsRequired).toBe(0);
484-
expect(detail.checks).toEqual([]);
495+
expect(detail.checks).toEqual([
496+
...sameRepositoryChecks,
497+
{
498+
name: "CI",
499+
status: "pending",
500+
description: "This workflow run has not finished.",
501+
url: "https://github.com/acme/web/actions/runs/202",
502+
},
503+
]);
485504
}).pipe(
486505
Effect.provide(
487506
Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
488507
revalidateChecks: (_input, read) => read,
489-
getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),
508+
getPullRequestDetail: () =>
509+
Effect.succeed({ ...openDetail, isCrossRepository: false, checks: sameRepositoryChecks }),
510+
// Run 201 is represented by its running job; run 202 is queued before any job exists.
511+
listUnfinishedWorkflowRuns: () =>
512+
Effect.succeed([
513+
{ id: 201, name: "Lint", url: "https://github.com/acme/web/actions/runs/201" },
514+
{ id: 202, name: "CI", url: "https://github.com/acme/web/actions/runs/202" },
515+
]),
490516
listWorkflowRunsRequiringApproval: () =>
491517
Effect.die("same-repository pull requests must not probe fork workflow approvals"),
492518
getViewerAccess: () =>
@@ -528,6 +554,7 @@ it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>
528554
Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
529555
revalidateChecks: (_input, read) => read,
530556
getPullRequestDetail: () => Effect.succeed(openDetail),
557+
listUnfinishedWorkflowRuns: () => Effect.succeed([]),
531558
listWorkflowRunsRequiringApproval: () =>
532559
Effect.fail(
533560
new GitHubPullRequestApi.GitHubWorkflowApprovalRefusedError({

‎packages/source-control-github/src/server/GitHubPullRequestProvider.ts‎

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,9 @@ function withAvatar(
161161
return avatarUrl === null ? actor : { ...actor, avatarUrl };
162162
}
163163

164+
const workflowRunIdOf = (url: string | null) =>
165+
url?.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1] ?? null;
166+
164167
function withWorkflowApprovals(
165168
checks: ReadonlyArray<PullRequestCheck>,
166169
runs: ReadonlyArray<GitHubWorkflowRunApproval>,
@@ -169,8 +172,8 @@ function withWorkflowApprovals(
169172
const representedRunIds = new Set<number>();
170173
for (const check of checks) {
171174
if (check.status !== "action-required" || check.url === null) continue;
172-
const id = check.url.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1];
173-
if (id !== undefined) representedRunIds.add(Number(id));
175+
const id = workflowRunIdOf(check.url);
176+
if (id !== null) representedRunIds.add(Number(id));
174177
}
175178
const approvalChecks = runs
176179
.filter((run) => !representedRunIds.has(run.id))
@@ -197,6 +200,30 @@ function withWorkflowApprovals(
197200
];
198201
}
199202

203+
// GitHub adds a run's check runs only as its jobs start, so a queued run can have none yet.
204+
function withUnfinishedWorkflowRuns(
205+
checks: ReadonlyArray<PullRequestCheck>,
206+
runs: ReadonlyArray<GitHubWorkflowRunApproval>,
207+
): ReadonlyArray<PullRequestCheck> {
208+
const runningRunIds = new Set<number>();
209+
for (const check of checks) {
210+
if (check.status !== "pending" && check.status !== "action-required") continue;
211+
const id = workflowRunIdOf(check.url);
212+
if (id !== null) runningRunIds.add(Number(id));
213+
}
214+
return [
215+
...checks,
216+
...runs
217+
.filter((run) => !runningRunIds.has(run.id))
218+
.map((run): PullRequestCheck => ({
219+
name: run.name,
220+
status: "pending",
221+
description: "This workflow run has not finished.",
222+
url: run.url,
223+
})),
224+
];
225+
}
226+
200227
/** App logins have no profile page; guessed avatar URLs 404. */
201228
export function loginAvatarUrl(login: string, host: string): string | null {
202229
return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
@@ -338,11 +365,24 @@ export const make = Effect.gen(function* () {
338365
}),
339366
)
340367
).pipe(
341-
Effect.map((workflowApprovals) => ({
368+
Effect.zip(
369+
pullRequest.state !== "open" || pullRequest.headSha == null
370+
? Effect.succeed([] as ReadonlyArray<GitHubWorkflowRunApproval>)
371+
: cli.listUnfinishedWorkflowRuns({ ...input, headSha: pullRequest.headSha }).pipe(
372+
Effect.catchIf(
373+
(error) =>
374+
error._tag !== "GitHubApiRateLimitError" &&
375+
error._tag !== "SourceControlRateLimitPausedError",
376+
() => Effect.succeed([] as ReadonlyArray<GitHubWorkflowRunApproval>),
377+
),
378+
),
379+
{ concurrent: true },
380+
),
381+
Effect.map(([workflowApprovals, unfinishedRuns]) => ({
342382
...pullRequest,
343383
author: withAvatar(pullRequest.author, new Map(), input.host),
344384
checks: withWorkflowApprovals(
345-
pullRequest.checks,
385+
withUnfinishedWorkflowRuns(pullRequest.checks, unfinishedRuns),
346386
workflowApprovals.runs,
347387
workflowApprovals.unavailable,
348388
),

‎packages/source-control-github/src/server/gitHubPullRequestJson.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ const RawWorkflowRunsSchema = Schema.Struct({
216216
id: Schema.Int,
217217
name: Schema.optional(Schema.NullOr(Schema.String)),
218218
html_url: Schema.optional(Schema.NullOr(Schema.String)),
219+
status: Schema.optional(Schema.NullOr(Schema.String)),
219220
}),
220221
),
221222
});
@@ -1124,6 +1125,32 @@ export function decodeWorkflowRunsJson(
11241125
});
11251126
}
11261127

1128+
// Approval-gated runs (action_required) are read separately as action-required checks.
1129+
const UNFINISHED_WORKFLOW_RUN_STATUSES = new Set([
1130+
"requested",
1131+
"queued",
1132+
"pending",
1133+
"waiting",
1134+
"in_progress",
1135+
]);
1136+
1137+
/** Workflow runs GitHub has not finished, which may have no check runs on the head yet. */
1138+
export function decodeUnfinishedWorkflowRunsJson(
1139+
raw: string,
1140+
): Result.Result<ReadonlyArray<GitHubWorkflowRunApproval>, DecodeFailure> {
1141+
const decoded = decodeWorkflowRuns(raw);
1142+
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
1143+
return Result.succeed(
1144+
decoded.success.workflow_runs
1145+
.filter((run) => UNFINISHED_WORKFLOW_RUN_STATUSES.has(run.status ?? ""))
1146+
.map((run) => ({
1147+
id: run.id,
1148+
name: trimmed(run.name) ?? `Workflow run ${run.id}`,
1149+
url: trimmed(run.html_url),
1150+
})),
1151+
);
1152+
}
1153+
11271154
export function toPullRequestHeads(result: PullRequestHeads.Result): {
11281155
readonly heads: ReadonlyArray<GitHubPullRequestHead>;
11291156
readonly nextCursor: string | null;

0 commit comments

Comments
 (0)