Skip to content

Commit 23132f8

Browse files
Radu028claudemaria-rcks
authored
fix(github): pull requests missing refs/pull/N/head no longer show as not found (pingdotgg#25947)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 358bb71 commit 23132f8

5 files changed

Lines changed: 236 additions & 27 deletions

File tree

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

Lines changed: 114 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ const refusedReviewer = {
4242
message: "Resource not accessible by integration",
4343
path: ["repository", "pullRequest", "reviewRequests", "nodes", 0, "requestedReviewer"],
4444
};
45+
// What GitHub answers for a pull request that has no `refs/pull/<number>/head`.
46+
const unresolvedPullRef = {
47+
type: "NOT_FOUND",
48+
message: "Could not resolve head ref 'refs/pull/7/head'.",
49+
path: ["repository", "pullRequest", "baseRef", "compare"],
50+
};
4551
const pullRequestInput = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 };
4652
type PullRequestRead = (
4753
input: typeof pullRequestInput,
@@ -2550,6 +2556,23 @@ layer("GitHubPullRequestApi.layer", (it) => {
25502556
}),
25512557
);
25522558

2559+
it.effect.each([
2560+
{ action: "merge", mutation: "mergePullRequest(" },
2561+
{ action: "update-branch", mutation: "updatePullRequestBranch(" },
2562+
] as const)("runs $action on a pull request GitHub has no pull ref for", ({ action, mutation }) =>
2563+
Effect.gen(function* () {
2564+
route([
2565+
"query PullRequestActionState",
2566+
{ ...actionState({ baseRef: { compare: null } }), errors: [unresolvedPullRef] },
2567+
]);
2568+
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2569+
2570+
yield* cli.runPullRequestAction({ ...pullRequestInput, action });
2571+
2572+
expect(variablesOf(mutation)).toHaveLength(1);
2573+
}),
2574+
);
2575+
25532576
it.effect("merges at once when auto-merge is asked of a pull request that is ready now", () =>
25542577
Effect.gen(function* () {
25552578
route(["query PullRequestActionState", actionState({ mergeStateStatus: "CLEAN" })]);
@@ -3461,7 +3484,12 @@ layer("GitHubPullRequestApi.layer", (it) => {
34613484
}).pipe(Effect.asVoid, Effect.flip);
34623485
expect(error._tag).toBe(tag ?? "GitHubApiResponseError");
34633486
if (error._tag === "GitHubApiResponseError")
3464-
expect(error).toMatchObject({ status, githubErrors: errors.map((e) => e.message) });
3487+
expect(error).toMatchObject({
3488+
status,
3489+
githubErrors: errors.map((e) =>
3490+
"path" in e ? `${e.message} (at ${e.path.join(".")})` : e.message,
3491+
),
3492+
});
34653493
expect(mockedExecute).toHaveBeenCalledTimes(index + 1);
34663494
}
34673495
}),
@@ -3577,6 +3605,91 @@ layer("GitHubPullRequestApi.layer", (it) => {
35773605
}),
35783606
);
35793607

3608+
const unresolvedCore = {
3609+
...coreResponse({ baseRef: { compare: null } }),
3610+
errors: [unresolvedPullRef],
3611+
};
3612+
it.effect.each([
3613+
{ description: "alone", answers: [unresolvedCore], requestedReviewers: [100] },
3614+
{
3615+
description: "beside a refused reviewer",
3616+
answers: [
3617+
{ ...unresolvedCore, errors: [unresolvedPullRef, refusedReviewer] },
3618+
unresolvedCore,
3619+
],
3620+
requestedReviewers: [100, 0],
3621+
},
3622+
])(
3623+
"reads a pull request without a pull ref, its comparison unknown ($description)",
3624+
({ answers, requestedReviewers }) =>
3625+
Effect.gen(function* () {
3626+
for (const answer of answers)
3627+
mockedExecute.mockReturnValueOnce(Effect.succeed(output(encodeJson(answer))));
3628+
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3629+
const detail = yield* cli.getPullRequestDetail(pullRequestInput);
3630+
expect(detail.number).toBe(7);
3631+
expect(detail.comparison).toBeNull();
3632+
expect(variablesOf("PullRequestCore").map((v) => v["requestedReviewers"])).toEqual(
3633+
requestedReviewers,
3634+
);
3635+
}),
3636+
);
3637+
3638+
it.effect("fails a missing pull ref beside another error, in GitHub's words", () =>
3639+
Effect.gen(function* () {
3640+
const refusedChecks = {
3641+
type: "FORBIDDEN",
3642+
message: "Resource not accessible by integration",
3643+
path: ["repository", "pullRequest", "commits", "nodes", 0, "commit", "statusCheckRollup"],
3644+
};
3645+
mockedExecute.mockReturnValueOnce(
3646+
Effect.succeed(
3647+
output(encodeJson({ ...unresolvedCore, errors: [unresolvedPullRef, refusedChecks] })),
3648+
),
3649+
);
3650+
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3651+
const error = yield* Effect.flip(cli.getPullRequestDetail(pullRequestInput));
3652+
expect(error).toMatchObject({
3653+
_tag: "GitHubApiResponseError",
3654+
status: 200,
3655+
githubErrors: [
3656+
"Could not resolve head ref 'refs/pull/7/head'. (at repository.pullRequest.baseRef.compare)",
3657+
"Resource not accessible by integration (at repository.pullRequest.commits.nodes.0.commit.statusCheckRollup)",
3658+
],
3659+
});
3660+
}),
3661+
);
3662+
3663+
it.effect("still reads a pull request GitHub cannot find as missing, in GitHub's words", () =>
3664+
Effect.gen(function* () {
3665+
const { data } = coreResponse();
3666+
mockedExecute.mockReturnValueOnce(
3667+
Effect.succeed(
3668+
output(
3669+
encodeJson({
3670+
data: { repository: { ...data.repository, pullRequest: null } },
3671+
errors: [
3672+
{
3673+
type: "NOT_FOUND",
3674+
message: "Could not resolve to a PullRequest with the number of 7.",
3675+
path: ["repository", "pullRequest"],
3676+
},
3677+
],
3678+
}),
3679+
),
3680+
),
3681+
);
3682+
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
3683+
const error = yield* Effect.flip(cli.getPullRequestDetail(pullRequestInput));
3684+
expect(error).toMatchObject({
3685+
_tag: "GitHubApiNotFoundError",
3686+
githubErrors: [
3687+
"Could not resolve to a PullRequest with the number of 7. (at repository.pullRequest)",
3688+
],
3689+
});
3690+
}),
3691+
);
3692+
35803693
it.effect.each([false, true])(
35813694
"continues after the core check page without reading it twice (reviewer refusal: %s)",
35823695
(refused) =>

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

Lines changed: 61 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,11 @@ import {
5555
PullRequestMutationsGraphQLGroup,
5656
type PullRequestActionSummary,
5757
} from "./pullRequestMutations.graphql.ts";
58-
import { PullRequestReadsGraphQLGroup } from "./pullRequestReads.graphql.ts";
58+
import {
59+
PullRequestActionState,
60+
PullRequestCore,
61+
PullRequestReadsGraphQLGroup,
62+
} from "./pullRequestReads.graphql.ts";
5963
import { PullRequestReviewsGraphQLGroup } from "./pullRequestReviews.graphql.ts";
6064
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
6165
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
@@ -321,23 +325,54 @@ const isGraphQlClientError = (error: unknown): error is GraphQLClientError.Graph
321325

322326
const { isNotFoundOnly } = GitHubGraphQlClient;
323327

328+
const isMissingPullRef = ({ path, type }: GraphQLClientError.GraphQLError): boolean =>
329+
type === "NOT_FOUND" && path?.join(".") === "repository.pullRequest.baseRef.compare";
330+
324331
const isRefusedRequestedReviewersOnly = (error: unknown): boolean =>
325332
isGraphQlClientError(error) &&
326333
error.reason._tag === "ResponseError" &&
327334
error.reason.status === 200 &&
328-
error.reason.errors.every(
329-
({ path, type }) =>
330-
type === "FORBIDDEN" &&
331-
path?.length === 6 &&
332-
path[0] === "repository" &&
333-
path[1] === "pullRequest" &&
334-
path[2] === "reviewRequests" &&
335-
path[3] === "nodes" &&
336-
typeof path[4] === "number" &&
337-
Number.isInteger(path[4]) &&
338-
path[4] >= 0 &&
339-
path[5] === "requestedReviewer",
340-
);
335+
// A missing pull ref can come along; the retried read tolerates it.
336+
error.reason.errors.every((graphQlError) => {
337+
const { path, type } = graphQlError;
338+
return (
339+
isMissingPullRef(graphQlError) ||
340+
(type === "FORBIDDEN" &&
341+
path?.length === 6 &&
342+
path[0] === "repository" &&
343+
path[1] === "pullRequest" &&
344+
path[2] === "reviewRequests" &&
345+
path[3] === "nodes" &&
346+
typeof path[4] === "number" &&
347+
Number.isInteger(path[4]) &&
348+
path[4] >= 0 &&
349+
path[5] === "requestedReviewer")
350+
);
351+
});
352+
353+
const isMissingPullRefOnly = <E>(
354+
error: E,
355+
): error is E &
356+
GraphQLClientError.GraphQLClientError & { readonly reason: GraphQLClientError.ResponseError } =>
357+
isGraphQlClientError(error) &&
358+
error.reason._tag === "ResponseError" &&
359+
error.reason.status === 200 &&
360+
error.reason.errors.every(isMissingPullRef);
361+
362+
/**
363+
* GitHub can lack `refs/pull/<number>/head` for a pull request it otherwise answers, and then
364+
* fails only the comparison against it. The rest of that answer stands, its comparison unknown.
365+
*/
366+
const toleratingMissingPullRef =
367+
<A, R2>(decode: (data: unknown) => Effect.Effect<A, Schema.SchemaError, R2>) =>
368+
<E, R>(effect: Effect.Effect<A, E, R>) =>
369+
effect.pipe(
370+
Effect.catchIf(isMissingPullRefOnly, (error) =>
371+
decode(error.reason.data).pipe(Effect.mapError(() => error)),
372+
),
373+
);
374+
const decodePullRequestCore = Schema.decodeUnknownEffect(PullRequestCore.result);
375+
const decodePullRequestActionState = Schema.decodeUnknownEffect(PullRequestActionState.result);
341376

342377
/** A large pull request can produce a multi-megabyte patch; past this it is truncated. */
343378
const DIFF_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
@@ -1457,14 +1492,16 @@ export const make = Effect.gen(function* () {
14571492
const { owner, name } = parseRepositorySelector(input.repository);
14581493
const operation = "getPullRequestDetail";
14591494
const read = (requestedReviewers: number) =>
1460-
client.PullRequestCore({
1461-
owner,
1462-
name,
1463-
number: input.number,
1464-
headRef: `refs/pull/${input.number}/head`,
1465-
required: asksRequired(input.host),
1466-
requestedReviewers,
1467-
});
1495+
client
1496+
.PullRequestCore({
1497+
owner,
1498+
name,
1499+
number: input.number,
1500+
headRef: `refs/pull/${input.number}/head`,
1501+
required: asksRequired(input.host),
1502+
requestedReviewers,
1503+
})
1504+
.pipe(toleratingMissingPullRef(decodePullRequestCore));
14681505
return SourceControlRateLimit.Interactive.pipe(
14691506
Effect.flatMap((allowReserve) =>
14701507
readRequestedReviewers(input, 100, read).pipe(
@@ -1693,6 +1730,7 @@ export const make = Effect.gen(function* () {
16931730
? new GitHubRequestPolicy.GitHubApiNotFoundError({
16941731
host: input.host,
16951732
operation: input.operation,
1733+
githubErrors: GitHubGraphQlClient.describeErrors(error),
16961734
})
16971735
: readError(input.cwd, input.operation, error),
16981736
),
@@ -2637,6 +2675,7 @@ export const make = Effect.gen(function* () {
26372675
headRef: `refs/pull/${input.number}/head`,
26382676
})
26392677
.pipe(
2678+
toleratingMissingPullRef(decodePullRequestActionState),
26402679
graphql({ ...target, allowReserve: true }),
26412680
Effect.map((result) => result.repository?.pullRequest ?? null),
26422681
Effect.flatMap(found(target)),

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,12 +69,17 @@ export class GitHubApiNotFoundError extends Schema.TaggedError<GitHubApiNotFound
6969
{
7070
host: Schema.String,
7171
operation: Schema.String,
72+
githubErrors: Schema.optionalKey(Schema.Array(Schema.String)),
7273
/** The source of the credential the refused request carried, when known. */
7374
credential: Schema.optionalKey(GitHubCredentials.GitHubCredentialSource),
7475
},
7576
) {
7677
override get message(): string {
77-
return "GitHub could not find the requested resource, or the credential cannot see it.";
78+
const missing =
79+
"GitHub could not find the requested resource, or the credential cannot see it.";
80+
return this.githubErrors !== undefined && this.githubErrors.length > 0
81+
? `${missing} GitHub said: ${this.githubErrors.join("; ")}`
82+
: missing;
7883
}
7984
}
8085

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

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,9 @@ describe("call", () => {
288288
const { layer } = harness(() =>
289289
json({
290290
data: { repository: null },
291-
errors: [{ type: "NOT_FOUND", message: "Could not resolve to a Repository" }],
291+
errors: [
292+
{ type: "NOT_FOUND", path: ["repository"], message: "Could not resolve to a Repository" },
293+
],
292294
}),
293295
);
294296
return Effect.gen(function* () {
@@ -297,10 +299,39 @@ describe("call", () => {
297299
_tag: "GitHubApiNotFoundError",
298300
host: "github.com",
299301
operation: "stats",
302+
githubErrors: ["Could not resolve to a Repository (at repository)"],
300303
});
301304
}).pipe(Effect.provide(layer));
302305
});
303306

307+
it.effect(
308+
"fails a NOT_FOUND below the pull request as GitHub's reason, not a missing one",
309+
() => {
310+
const { layer } = harness(() =>
311+
json({
312+
data: { repository: { pullRequest: stats } },
313+
errors: [
314+
{
315+
type: "NOT_FOUND",
316+
path: ["repository", "pullRequest", "baseRef", "compare"],
317+
message: "Could not resolve head ref 'refs/pull/7/head'.",
318+
},
319+
],
320+
}),
321+
);
322+
return Effect.gen(function* () {
323+
const error = yield* Effect.flip(callStats());
324+
expect(error).toMatchObject({
325+
_tag: "GitHubApiResponseError",
326+
status: 200,
327+
githubErrors: [
328+
"Could not resolve head ref 'refs/pull/7/head'. (at repository.pullRequest.baseRef.compare)",
329+
],
330+
});
331+
}).pipe(Effect.provide(layer));
332+
},
333+
);
334+
304335
it.effect(
305336
"fails NOT_FOUND alongside another error as a failure carrying GitHub's reasons",
306337
() => {

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

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,31 @@ function queryHash(query: string): string {
4343
return (hash >>> 0).toString(16).padStart(8, "0");
4444
}
4545

46+
/**
47+
* Whether every error is a NOT_FOUND on a lookup: a root field (with its list items),
48+
* `repository.pullRequest` or `repository.issueOrPullRequest`. A NOT_FOUND deeper down is one
49+
* field GitHub could not resolve.
50+
*/
4651
export const isNotFoundOnly = (error: unknown): boolean =>
4752
GraphQLClientError.isGraphQLClientError(error) &&
4853
error.reason._tag === "ResponseError" &&
49-
error.reason.errors.every((graphQlError) => graphQlError["type"] === "NOT_FOUND");
54+
error.reason.errors.every(
55+
({ type, path }) =>
56+
type === "NOT_FOUND" &&
57+
(path === undefined ||
58+
path.slice(1).every((segment) => typeof segment === "number") ||
59+
(path.length === 2 &&
60+
path[0] === "repository" &&
61+
(path[1] === "pullRequest" || path[1] === "issueOrPullRequest"))),
62+
);
63+
64+
/** GitHub's message for each error in an answer, with the field it names. */
65+
export const describeErrors = (error: GraphQLClientError.GraphQLClientError) =>
66+
error.reason._tag === "ResponseError"
67+
? error.reason.errors.map(({ message, path }) =>
68+
path === undefined || path.length === 0 ? message : `${message} (at ${path.join(".")})`,
69+
)
70+
: [];
5071

5172
/** Share REST's credentials/slots/quota/pause; leave non-rate-limit errors to each lookup. */
5273
export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
@@ -234,6 +255,7 @@ const fromClientError = (
234255
const context = {
235256
host: normalizeHost(target.host),
236257
operation: target.operation,
258+
githubErrors: describeErrors(error),
237259
};
238260
const credential = Option.filter(
239261
Headers.get(reason.headers ?? Headers.empty, CREDENTIAL_SOURCE_HEADER),
@@ -247,7 +269,6 @@ const fromClientError = (
247269
: new GitHubRequestPolicy.GitHubApiResponseError({
248270
...context,
249271
status: reason.status ?? 200,
250-
githubErrors: reason.errors.map((graphQlError) => graphQlError.message),
251272
githubErrorTypes: reason.errors.map((graphQlError) =>
252273
typeof graphQlError["type"] === "string" ? graphQlError["type"] : null,
253274
),

0 commit comments

Comments
 (0)