fix(server): background GitHub polling uses ~74% fewer calls with batched GraphQL (#14673)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
a3abb52660
commit
10ac2f2ba4
15 files changed
+1039
-213
No files matched your search
@@ -13,6 +13,7 @@ import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as References from "effect/References";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import { TestClock } from "effect/testing";
|
||||
@@ -32,6 +33,7 @@ import {
|
||||
TextGenerationError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import { decodeGitHubPullRequestListJson } from "../sourceControl/gitHubPullRequests.ts";
|
||||
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
@@ -510,6 +512,30 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return {
|
||||
service: {
|
||||
execute,
|
||||
// The fake answers the CLI shape, so batched lookups read it the way the fallback does.
|
||||
listPullRequestsByHead: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headSelector,
|
||||
"--state",
|
||||
input.state,
|
||||
"--limit",
|
||||
String(input.limit),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
const raw = result.stdout.trim();
|
||||
if (raw.length === 0) return [];
|
||||
const decoded = decodeGitHubPullRequestListJson(raw);
|
||||
return Result.isSuccess(decoded) ? decoded.success : [];
|
||||
}),
|
||||
),
|
||||
listOpenPullRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
|
||||
@@ -754,6 +754,88 @@ describe("PullRequestSyncReactor", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads a burst of requested links in one sweep", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(Date.parse(NOW));
|
||||
const reading = yield* Deferred.make<void>();
|
||||
const release = yield* Deferred.make<void>();
|
||||
const fixture = yield* makeHarness({
|
||||
snapshot: makeSnapshot([]),
|
||||
summary: (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.number === 1) {
|
||||
yield* Deferred.succeed(reading, undefined);
|
||||
yield* Deferred.await(release);
|
||||
}
|
||||
return makeSummary(input);
|
||||
}),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const reactor = yield* startAndSweep(fixture);
|
||||
yield* Ref.set(
|
||||
fixture.snapshots,
|
||||
makeSnapshot(
|
||||
[1, 2, 3, 4].map((number) =>
|
||||
makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
|
||||
),
|
||||
),
|
||||
);
|
||||
const request = (number: number) =>
|
||||
reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
|
||||
yield* request(1);
|
||||
yield* Deferred.await(reading);
|
||||
yield* Effect.forEach([2, 3, 4], request, { discard: true });
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
yield* reactor.drain;
|
||||
// One sweep for the first link and one for the three that arrived while it read.
|
||||
assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
|
||||
[1, 2, 3, 4],
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("skips the stack read for a pull request the summary places in no stack", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(Date.parse(NOW));
|
||||
const fixture = yield* makeHarness({
|
||||
snapshot: makeSnapshot([
|
||||
makeThread("unstacked", { pullRequests: [makeLink(1)] }),
|
||||
makeThread("stacked", { pullRequests: [makeLink(2)] }),
|
||||
makeThread("unknown", { pullRequests: [makeLink(3)] }),
|
||||
]),
|
||||
summary: (input) =>
|
||||
Effect.succeed(
|
||||
makeSummary(
|
||||
input,
|
||||
input.number === 1
|
||||
? { stack: null }
|
||||
: input.number === 2
|
||||
? { stack: { number: 9, position: 1, size: 2, base: "main" } }
|
||||
: {},
|
||||
),
|
||||
),
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* startAndSweep(fixture);
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
|
||||
[2, 3],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
|
||||
[1, 2, 3],
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("polls open pull requests on settled threads every fifteen minutes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -133,6 +133,9 @@ export const make = Effect.gen(function* () {
|
||||
const lastSyncedAt = new Map<string, number>();
|
||||
const requested = new Map<string, number>();
|
||||
let requestGeneration = 0;
|
||||
// Requested keys wait in `requested` for one queued sweep, so a burst of links (an agent
|
||||
// linking dozens of pull requests) is read together and shares the summary batches.
|
||||
let requestedSweepQueued = false;
|
||||
const retryStacks = new Set<string>();
|
||||
|
||||
const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
|
||||
@@ -151,7 +154,8 @@ export const make = Effect.gen(function* () {
|
||||
<E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
|
||||
Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
|
||||
|
||||
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (requestedKey?: string) {
|
||||
/** `requested` reads only keys asked for through `requestSync`; `all` is the periodic pass. */
|
||||
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
|
||||
const threads = yield* snapshots.listThreadsWithPullRequests();
|
||||
const now = yield* DateTime.now;
|
||||
const nowMs = DateTime.toEpochMillis(now);
|
||||
@@ -250,22 +254,31 @@ export const make = Effect.gen(function* () {
|
||||
retryStacks.has(key) ||
|
||||
entries.some(
|
||||
(entry) =>
|
||||
entry.link.snapshot === null || !snapshotFieldsEqual(entry.link.snapshot, fields),
|
||||
entry.link.snapshot === null ||
|
||||
!snapshotFieldsEqual(entry.link.snapshot, fields) ||
|
||||
(summary.stack !== undefined &&
|
||||
(entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
|
||||
);
|
||||
const fetchedStack = needsStack
|
||||
? yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
|
||||
Effect.map((stack) => ({
|
||||
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
|
||||
})),
|
||||
Effect.catchCauseIf(
|
||||
(cause) => !Cause.hasInterruptsOnly(cause),
|
||||
() =>
|
||||
Effect.logWarning("pull request stack lookup failed", {
|
||||
key,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
// A summary that says the pull request is in no stack, for links that hold none, already
|
||||
// answers what the stack read would.
|
||||
const knownUnstacked =
|
||||
summary.stack === null && entries.every((entry) => entry.link.stack === null);
|
||||
const fetchedStack = !needsStack
|
||||
? null
|
||||
: knownUnstacked
|
||||
? { stack: null }
|
||||
: yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
|
||||
Effect.map((stack) => ({
|
||||
stack: stack === null ? null : ({ kind: "native", ...stack } as const),
|
||||
})),
|
||||
Effect.catchCauseIf(
|
||||
(cause) => !Cause.hasInterruptsOnly(cause),
|
||||
() =>
|
||||
Effect.logWarning("pull request stack lookup failed", {
|
||||
key,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
if (needsStack) {
|
||||
if (fetchedStack === null) {
|
||||
retryStacks.add(key);
|
||||
@@ -296,7 +309,7 @@ export const make = Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
groups,
|
||||
([key, entries]) =>
|
||||
(requestedKey === undefined || requestedKey === key) && isDue(key, entries, nowMs)
|
||||
(scope === "all" || requested.has(key)) && isDue(key, entries, nowMs)
|
||||
? syncGroup(key, entries).pipe(
|
||||
Effect.catchCause(logSkipped("pull request sync skipped", { key })),
|
||||
)
|
||||
@@ -307,8 +320,12 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const worker = yield* makeDrainableWorker((key: string | undefined) =>
|
||||
sweep(key).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
|
||||
const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
|
||||
Effect.suspend(() => {
|
||||
// Requests from here on queue another sweep; the ones already recorded are read by this.
|
||||
if (scope === "requested") requestedSweepQueued = false;
|
||||
return sweep(scope);
|
||||
}).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
|
||||
);
|
||||
|
||||
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
|
||||
@@ -322,7 +339,7 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
yield* forkParked(
|
||||
Effect.gen(function* () {
|
||||
yield* worker.enqueue(undefined);
|
||||
yield* worker.enqueue("all");
|
||||
yield* worker.drain;
|
||||
}).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
|
||||
);
|
||||
@@ -330,9 +347,10 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
|
||||
Effect.suspend(() => {
|
||||
const syncKey = threadPullRequestKeyOf(key);
|
||||
requested.set(syncKey, ++requestGeneration);
|
||||
return worker.enqueue(syncKey);
|
||||
requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
|
||||
if (requestedSweepQueued) return Effect.void;
|
||||
requestedSweepQueued = true;
|
||||
return worker.enqueue("requested");
|
||||
});
|
||||
|
||||
return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
|
||||
|
||||
@@ -348,7 +348,9 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
|
||||
),
|
||||
),
|
||||
{ concurrency: 8, discard: true },
|
||||
// Wide enough that a sweep's GitHub branch lookups reach GitHubCli together and share one
|
||||
// GraphQL document, instead of one `gh pr list` per branch.
|
||||
{ concurrency: 32, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1821,7 +1821,12 @@ export const make = Effect.gen(function* () {
|
||||
const batchable = entries.filter(
|
||||
(entry) => buildPullRequestSummariesGraphQlQuery([entry.request]) !== null,
|
||||
);
|
||||
const query = buildPullRequestSummariesGraphQlQuery(batchable.map((entry) => entry.request));
|
||||
// Stack membership rides along where GitHub serves stacks, so the background sync can skip
|
||||
// the REST stack read for pull requests that are in none.
|
||||
const query = buildPullRequestSummariesGraphQlQuery(
|
||||
batchable.map((entry) => entry.request),
|
||||
first.request.host === "github.com",
|
||||
);
|
||||
const batched =
|
||||
query === null
|
||||
? Effect.succeed(new Map<number, GitHubPullRequestSummary>())
|
||||
|
||||
@@ -116,6 +116,11 @@ export interface ProviderChangeRequestSummary {
|
||||
readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
|
||||
readonly checksState?: PullRequestChecksState | null | undefined;
|
||||
readonly mergeability?: PullRequestMergeability | undefined;
|
||||
/**
|
||||
* The host-native stack the pull request sits in, from the same read. Null when the host says
|
||||
* it is in none; absent when the read did not ask.
|
||||
*/
|
||||
readonly stack?: PullRequestStackMembership | null | undefined;
|
||||
}
|
||||
|
||||
/** One layer of a host-native stack, bottom to top order is the array's. */
|
||||
|
||||
@@ -1596,6 +1596,7 @@ export const make = Effect.gen(function* () {
|
||||
...(changeRequest.mergeability === undefined
|
||||
? {}
|
||||
: { mergeability: changeRequest.mergeability }),
|
||||
...(changeRequest.stack === undefined ? {} : { stack: changeRequest.stack }),
|
||||
})),
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -1934,5 +1934,43 @@ describe("batched pull request summaries", () => {
|
||||
mergeability: "unknown",
|
||||
additions: 0,
|
||||
});
|
||||
// The document did not ask about stacks, so the summary does not claim an answer.
|
||||
expect(decoded.success.get(0)).not.toHaveProperty("stack");
|
||||
});
|
||||
|
||||
it("reads stack membership only where the document asked for it", () => {
|
||||
expect(
|
||||
buildPullRequestSummariesGraphQlQuery([{ repository: "acme/web", number: 7 }], true),
|
||||
).toContain("stack { number size baseRefName } stackEntry { position }");
|
||||
expect(
|
||||
buildPullRequestSummariesGraphQlQuery([{ repository: "acme/web", number: 7 }]),
|
||||
).not.toContain("stack {");
|
||||
const pullRequest = (number: number, stack: Record<string, unknown>) => ({
|
||||
pullRequest: {
|
||||
number,
|
||||
title: "Stacked",
|
||||
url: `https://github.com/acme/web/pull/${number}`,
|
||||
headRefName: `feat/${number}`,
|
||||
baseRefName: "main",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-08-24T00:00:00Z",
|
||||
...stack,
|
||||
},
|
||||
});
|
||||
const decoded = expectSuccess(
|
||||
decodePullRequestSummariesJson(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
s0: pullRequest(7, { stack: null, stackEntry: null }),
|
||||
s1: pullRequest(8, {
|
||||
stack: { number: 3, size: 2, baseRefName: "main" },
|
||||
stackEntry: { position: 2 },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(decoded.get(0)?.stack).toBeNull();
|
||||
expect(decoded.get(1)?.stack).toEqual({ number: 3, size: 2, base: "main", position: 2 });
|
||||
});
|
||||
});
|
||||
@@ -1852,6 +1852,8 @@ export function decodePullRequestStatsJson(
|
||||
* shape as the search row where the two overlap: the checks arrive as GitHub's one-word rollup
|
||||
* rather than the whole check list `gh pr view` hands back, which is what keeps a batch cheap.
|
||||
*/
|
||||
const STACK_MEMBERSHIP_SELECTION = "stack { number size baseRefName } stackEntry { position }";
|
||||
|
||||
const PULL_REQUEST_SUMMARY_SELECTION =
|
||||
"number title url state isDraft mergeable reviewDecision additions deletions changedFiles " +
|
||||
"updatedAt mergedAt closedAt headRefName baseRefName " +
|
||||
@@ -1865,6 +1867,7 @@ const PULL_REQUEST_SUMMARY_SELECTION =
|
||||
*/
|
||||
export function buildPullRequestSummariesGraphQlQuery(
|
||||
changeRequests: ReadonlyArray<{ readonly repository: string; readonly number: number }>,
|
||||
includeStacks = false,
|
||||
): string | null {
|
||||
if (changeRequests.length === 0) return null;
|
||||
const selections: string[] = [];
|
||||
@@ -1874,7 +1877,7 @@ export function buildPullRequestSummariesGraphQlQuery(
|
||||
if (!REPOSITORY_PART.test(owner) || !REPOSITORY_PART.test(name)) return null;
|
||||
if (!Number.isSafeInteger(changeRequest.number) || changeRequest.number <= 0) return null;
|
||||
selections.push(
|
||||
` s${index}: repository(owner: "${owner}", name: "${name}") { pullRequest(number: ${changeRequest.number}) { ${PULL_REQUEST_SUMMARY_SELECTION} } }`,
|
||||
` s${index}: repository(owner: "${owner}", name: "${name}") { pullRequest(number: ${changeRequest.number}) { ${PULL_REQUEST_SUMMARY_SELECTION}${includeStacks ? ` ${STACK_MEMBERSHIP_SELECTION}` : ""} } }`,
|
||||
);
|
||||
}
|
||||
return `query PullRequestSummaries {\n${selections.join("\n")}\n}`;
|
||||
@@ -1920,6 +1923,8 @@ export interface GitHubPullRequestSummary {
|
||||
readonly reviewDecision: PullRequestReviewDecision | null;
|
||||
readonly checksState: PullRequestChecksState | null;
|
||||
readonly mergeability: PullRequestMergeability;
|
||||
/** Null when GitHub says the pull request is in no stack; absent when the read did not ask. */
|
||||
readonly stack?: PullRequestStackMembership | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1965,6 +1970,7 @@ export function decodePullRequestSummariesJson(
|
||||
}),
|
||||
),
|
||||
mergeability: toMergeability(pr.mergeable),
|
||||
...(pr.stack === undefined ? {} : { stack: toStackMembership(pr) ?? null }),
|
||||
});
|
||||
}
|
||||
return Result.succeed(summaries);
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
@@ -31,13 +32,18 @@ const quotaOutput = (remaining = 5000, resetAt = "2099-01-01T00:00:00Z") =>
|
||||
JSON.stringify({ data: { rateLimit: { cost: 1, limit: 5000, remaining, resetAt } } }),
|
||||
);
|
||||
|
||||
const isBudgetReading = (input: VcsProcess.VcsProcessInput) =>
|
||||
input.args[0] === "api" &&
|
||||
input.args[1] === "graphql" &&
|
||||
input.args.at(-1)?.includes("rateLimit");
|
||||
|
||||
const mockRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();
|
||||
|
||||
// Budget readings are answered here, so `mockRun` sees only the commands under test.
|
||||
const layer = GitHubCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: (input) =>
|
||||
input.args[1] === "rate_limit" ? Effect.succeed(quotaOutput()) : mockRun(input),
|
||||
run: (input) => (isBudgetReading(input) ? Effect.succeed(quotaOutput()) : mockRun(input)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -46,9 +52,9 @@ afterEach(() => {
|
||||
mockRun.mockReset();
|
||||
});
|
||||
|
||||
it.effect("shares quota checks, preserves the reserve, and resumes after reset", () =>
|
||||
it.effect("reads the GraphQL budget once per window, preserves the reserve, and resumes", () =>
|
||||
Effect.gen(function* () {
|
||||
let probes = 0;
|
||||
let readings = 0;
|
||||
const commands: string[] = [];
|
||||
let remaining = 501;
|
||||
let resetAt = DateTime.formatIso(
|
||||
@@ -58,8 +64,8 @@ it.effect("shares quota checks, preserves the reserve, and resumes after reset",
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.args[1] === "rate_limit") {
|
||||
probes++;
|
||||
if (isBudgetReading(input)) {
|
||||
readings++;
|
||||
assert.strictEqual(input.args[3], "enterprise.test");
|
||||
return quotaOutput(remaining, resetAt);
|
||||
}
|
||||
@@ -79,24 +85,320 @@ it.effect("shares quota checks, preserves the reserve, and resumes after reset",
|
||||
yield* read("list");
|
||||
const failure = yield* read("view").pipe(Effect.flip);
|
||||
assert.strictEqual(failure._tag, "GitHubCliRateLimitError");
|
||||
assert.strictEqual(probes, 1);
|
||||
assert.deepStrictEqual(commands, ["pr list"]);
|
||||
yield* read("view").pipe(Effect.provideService(GitHubCli.AllowGitHubReserve, true));
|
||||
yield* gh.execute({ cwd: "/repo", args: ["pr", "merge", "1"] });
|
||||
assert.deepStrictEqual(commands, ["pr list", "pr view", "pr merge"]);
|
||||
remaining = 0;
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
yield* read("repo").pipe(Effect.flip);
|
||||
assert.strictEqual(probes, 2);
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
// One reading covers the whole window.
|
||||
assert.strictEqual(readings, 1);
|
||||
yield* TestClock.adjust("1 minute");
|
||||
remaining = 5000;
|
||||
resetAt = DateTime.formatIso(DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 60_000));
|
||||
yield* Effect.all([read("list"), read("repo")], { concurrency: 2 });
|
||||
assert.strictEqual(probes, 3);
|
||||
assert.strictEqual(readings, 2);
|
||||
assert.deepStrictEqual(commands.slice(3).toSorted(), ["pr list", "repo view"]);
|
||||
}).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
|
||||
);
|
||||
|
||||
it.effect("reads the budget again at a near reset, and every ten minutes in a long window", () =>
|
||||
Effect.gen(function* () {
|
||||
let readings = 0;
|
||||
const startedAt = yield* Clock.currentTimeMillis;
|
||||
let resetAt = DateTime.formatIso(DateTime.makeUnsafe(startedAt + 10_000));
|
||||
const gh = yield* GitHubCli.make.pipe(
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (!isBudgetReading(input)) return processOutput("[]");
|
||||
readings++;
|
||||
return quotaOutput(5000, resetAt);
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const read = gh.execute({ cwd: "/repo", args: ["pr", "list"] });
|
||||
yield* read;
|
||||
// The window resets ten seconds in, so the reading expires with it.
|
||||
resetAt = DateTime.formatIso(DateTime.makeUnsafe(startedAt + 10_000 + 3_600_000));
|
||||
yield* TestClock.adjust("10 seconds");
|
||||
yield* read;
|
||||
assert.strictEqual(readings, 2);
|
||||
yield* TestClock.adjust("9 minutes");
|
||||
yield* read;
|
||||
assert.strictEqual(readings, 2);
|
||||
yield* TestClock.adjust("1 minute");
|
||||
yield* read;
|
||||
assert.strictEqual(readings, 3);
|
||||
}).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
|
||||
);
|
||||
|
||||
it.effect("reads anyway when the budget reading fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli.make.pipe(
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
isBudgetReading(input)
|
||||
? Effect.fail(
|
||||
new VcsProcessSpawnError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
cwd: "/gone",
|
||||
cause: new Error("ENOENT"),
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(processOutput("[]")),
|
||||
}),
|
||||
);
|
||||
const result = yield* gh.execute({ cwd: "/repo", args: ["pr", "list"] });
|
||||
assert.strictEqual(result.stdout, "[]");
|
||||
}).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
|
||||
);
|
||||
|
||||
describe("selectGitHubBaseRepository", () => {
|
||||
const remotes = (...entries: ReadonlyArray<readonly [string, string]>) =>
|
||||
entries
|
||||
.flatMap(([name, url]) => [`${name}\t${url} (fetch)`, `${name}\t${url} (push)`])
|
||||
.join("\n");
|
||||
const select = (input: { remotes: string; resolved?: string }) =>
|
||||
GitHubCli.selectGitHubBaseRepository({ resolved: "", host: "github.com", ...input });
|
||||
|
||||
it("picks the repository gh reads without a prompt", () => {
|
||||
assert.deepStrictEqual(select({ remotes: remotes(["fork", "[email protected]:me/web.git"]) }), {
|
||||
owner: "me",
|
||||
name: "web",
|
||||
});
|
||||
const fork = remotes(
|
||||
["origin", "[email protected]:me/web.git"],
|
||||
["upstream", "https://github.com/Acme/Web.git"],
|
||||
);
|
||||
assert.deepStrictEqual(select({ remotes: fork }), { owner: "acme", name: "web" });
|
||||
assert.deepStrictEqual(select({ remotes: fork, resolved: "remote.origin.gh-resolved base" }), {
|
||||
owner: "me",
|
||||
name: "web",
|
||||
});
|
||||
assert.deepStrictEqual(
|
||||
select({ remotes: fork, resolved: "remote.origin.gh-resolved acme/other" }),
|
||||
{ owner: "acme", name: "other" },
|
||||
);
|
||||
// gh ranks remote names in any case.
|
||||
assert.deepStrictEqual(
|
||||
select({
|
||||
remotes: remotes(
|
||||
["origin", "[email protected]:me/web.git"],
|
||||
["Upstream", "[email protected]:acme/web.git"],
|
||||
),
|
||||
}),
|
||||
{ owner: "acme", name: "web" },
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves gh to choose when it might weigh the remotes differently", () => {
|
||||
for (const input of [
|
||||
{ remotes: "" },
|
||||
{
|
||||
remotes: remotes(["a", "[email protected]:me/web.git"], ["b", "[email protected]:acme/web.git"]),
|
||||
},
|
||||
{
|
||||
remotes: remotes(
|
||||
["origin", "[email protected]:me/web.git"],
|
||||
["mirror", "[email protected]:me/web.git"],
|
||||
),
|
||||
},
|
||||
{ remotes: remotes(["origin", "git@github-work:me/web.git"]) },
|
||||
{
|
||||
remotes: remotes(
|
||||
["origin", "[email protected]:me/web.git"],
|
||||
["Origin", "[email protected]:acme/web.git"],
|
||||
),
|
||||
},
|
||||
{
|
||||
remotes: remotes(
|
||||
["origin", "[email protected]:me/web.git"],
|
||||
["upstream", "[email protected]:acme/web.git"],
|
||||
),
|
||||
resolved: "remote.origin.gh-resolved base\nremote.upstream.gh-resolved base",
|
||||
},
|
||||
]) {
|
||||
assert.strictEqual(select(input), null);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("GitHubCli.listPullRequestsByHead", () => {
|
||||
const remoteOutput =
|
||||
"origin\[email protected]:acme/web.git (fetch)\norigin\[email protected]:acme/web.git (push)\n";
|
||||
const node = (number: number, headRefName: string) => ({
|
||||
number,
|
||||
title: `PR ${number}`,
|
||||
url: `https://github.com/acme/web/pull/${number}`,
|
||||
baseRefName: "main",
|
||||
headRefName,
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-02T00:00:00Z",
|
||||
headRepository: { name: "web", nameWithOwner: "acme/web" },
|
||||
headRepositoryOwner: { login: "acme" },
|
||||
});
|
||||
const decodeRequest = Schema.decodeSync(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
query: Schema.String,
|
||||
variables: Schema.Record(Schema.String, Schema.Unknown),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const jsonOutput = (value: unknown) => processOutput(JSON.stringify(value));
|
||||
const git = (input: VcsProcess.VcsProcessInput) =>
|
||||
input.args[0] === "remote"
|
||||
? processOutput(remoteOutput)
|
||||
: { ...processOutput(""), exitCode: ChildProcessSpawner.ExitCode(1) };
|
||||
|
||||
it.effect("reads heads on one repository in one GraphQL document", () =>
|
||||
Effect.gen(function* () {
|
||||
const documents: Array<{ query: string; variables: Record<string, unknown> }> = [];
|
||||
mockRun.mockImplementation((input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.command === "git") return git(input);
|
||||
documents.push(decodeRequest(input.stdin ?? ""));
|
||||
return jsonOutput({
|
||||
data: {
|
||||
repository: { h0: { nodes: [node(7, "feature/a")] }, h1: { nodes: [] } },
|
||||
rateLimit: { cost: 1, limit: 5000, remaining: 4999, resetAt: "2099-01-01T00:00:00Z" },
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const lookups = yield* Effect.all(
|
||||
["feature/a", "feature/b"].map((headSelector) =>
|
||||
gh.listPullRequestsByHead({
|
||||
cwd: "/repo",
|
||||
headSelector,
|
||||
state: "all",
|
||||
limit: 100,
|
||||
rateLimitHost: "github.com",
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.forkChild);
|
||||
yield* TestClock.adjust("50 millis");
|
||||
const [first, second] = yield* Fiber.join(lookups);
|
||||
assert.deepStrictEqual(
|
||||
first?.map((pr) => [pr.number, pr.state, pr.headRepositoryNameWithOwner]),
|
||||
[[7, "merged", "acme/web"]],
|
||||
);
|
||||
assert.deepStrictEqual(second, []);
|
||||
assert.strictEqual(documents.length, 1);
|
||||
assert.include(documents[0]!.query, "rateLimit");
|
||||
assert.deepStrictEqual(documents[0]!.variables, {
|
||||
owner: "acme",
|
||||
name: "web",
|
||||
h0: "feature/a",
|
||||
s0: ["OPEN", "CLOSED", "MERGED"],
|
||||
h1: "feature/b",
|
||||
s1: ["OPEN", "CLOSED", "MERGED"],
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("asks gh pr list when gh could read another repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<ReadonlyArray<string>> = [];
|
||||
mockRun.mockImplementation((input) =>
|
||||
Effect.sync(() => {
|
||||
commands.push([input.command, ...input.args]);
|
||||
if (input.command === "git") {
|
||||
return processOutput(
|
||||
input.args[0] === "remote"
|
||||
? "a\[email protected]:me/web.git (fetch)\nb\[email protected]:acme/web.git (fetch)\n"
|
||||
: "",
|
||||
);
|
||||
}
|
||||
return input.args[3] === "feature/empty"
|
||||
? processOutput("")
|
||||
: jsonOutput([node(8, "feature/a")]);
|
||||
}),
|
||||
);
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const pullRequests = yield* gh.listPullRequestsByHead({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/a",
|
||||
state: "all",
|
||||
limit: 100,
|
||||
rateLimitHost: "github.com",
|
||||
});
|
||||
assert.deepStrictEqual(
|
||||
pullRequests.map((pr) => pr.number),
|
||||
[8],
|
||||
);
|
||||
assert.deepStrictEqual(commands.at(-1), [
|
||||
"gh",
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
"feature/a",
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"100",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
]);
|
||||
const empty = yield* gh.listPullRequestsByHead({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/empty",
|
||||
state: "all",
|
||||
limit: 100,
|
||||
rateLimitHost: "github.com",
|
||||
});
|
||||
assert.deepStrictEqual(empty, []);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("fails a rate-limited document whole instead of asking head by head", () =>
|
||||
Effect.gen(function* () {
|
||||
let ghCalls = 0;
|
||||
mockRun.mockImplementation((input) => {
|
||||
if (input.command === "git") return Effect.succeed(git(input));
|
||||
ghCalls++;
|
||||
return Effect.fail(
|
||||
new VcsProcessExitError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
failureKind: "rate-limited",
|
||||
detail: "API rate limit exceeded.",
|
||||
stderrLength: 24,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
const lookups = yield* Effect.all(
|
||||
["feature/a", "feature/b"].map((headSelector) =>
|
||||
gh
|
||||
.listPullRequestsByHead({
|
||||
cwd: "/repo",
|
||||
headSelector,
|
||||
state: "all",
|
||||
limit: 100,
|
||||
rateLimitHost: "github.com",
|
||||
})
|
||||
.pipe(Effect.flip),
|
||||
),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.forkChild);
|
||||
yield* TestClock.adjust("50 millis");
|
||||
const errors = yield* Fiber.join(lookups);
|
||||
assert.deepStrictEqual(
|
||||
errors.map((error) => error._tag),
|
||||
["GitHubCliRateLimitError", "GitHubCliRateLimitError"],
|
||||
);
|
||||
assert.strictEqual(ghCalls, 1);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
|
||||
describe("GitHubCli.layer", () => {
|
||||
it.effect("shares the registry budget with CLI reads through nested layer providers", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -116,8 +418,9 @@ describe("GitHubCli.layer", () => {
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.args[1] === "rate_limit")
|
||||
if (isBudgetReading(input)) {
|
||||
return quotaOutput(input.env?.GH_TOKEN === "empty" ? 0 : 5000);
|
||||
}
|
||||
reads++;
|
||||
return processOutput("[]");
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -8,6 +9,8 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Request from "effect/Request";
|
||||
import * as RequestResolver from "effect/RequestResolver";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
@@ -16,11 +19,14 @@ import {
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
|
||||
import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestEntries,
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
type NormalizedGitHubPullRequestRecord,
|
||||
@@ -300,6 +306,20 @@ export class GitHubCli extends Context.Service<
|
||||
readonly rateLimitHost?: string;
|
||||
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Pull requests whose head is `headSelector`, in the repository `gh pr list` would read in
|
||||
* `cwd`. Lookups on one repository that arrive together share one GraphQL document; a
|
||||
* checkout whose repository gh could pick another way is asked through `gh pr list`.
|
||||
*/
|
||||
readonly listPullRequestsByHead: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly state: "open" | "closed" | "merged" | "all";
|
||||
readonly limit: number;
|
||||
/** The checkout's GitHub host. Without it the lookup is not batched. */
|
||||
readonly rateLimitHost?: string;
|
||||
}) => Effect.Effect<ReadonlyArray<NormalizedGitHubPullRequestRecord>, GitHubCliError>;
|
||||
|
||||
readonly getPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
@@ -394,6 +414,149 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
|
||||
};
|
||||
}
|
||||
|
||||
type PullRequestListState = "open" | "closed" | "merged" | "all";
|
||||
|
||||
const PULL_REQUEST_LIST_JSON_FIELDS =
|
||||
"number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner";
|
||||
/** The `gh pr list --json` fields above, as GraphQL selects them. */
|
||||
const PULL_REQUEST_NODE_SELECTION =
|
||||
"number title url baseRefName headRefName state isDraft mergedAt closedAt updatedAt isCrossRepository headRepository { name nameWithOwner } headRepositoryOwner { login }";
|
||||
const GRAPHQL_STATES: Record<PullRequestListState, ReadonlyArray<string>> = {
|
||||
open: ["OPEN"],
|
||||
closed: ["CLOSED"],
|
||||
merged: ["MERGED"],
|
||||
all: ["OPEN", "CLOSED", "MERGED"],
|
||||
};
|
||||
/**
|
||||
* Head lookups per GraphQL document. A document of a hundred costs one point, the same as one
|
||||
* `gh pr list`, but half that keeps each answer near half a second.
|
||||
*/
|
||||
const HEAD_LOOKUPS_PER_DOCUMENT = 50;
|
||||
/**
|
||||
* How long a head lookup waits for company. Branch discovery reaches GitHub only after each
|
||||
* branch's own git reads, so lookups started together arrive tens of milliseconds apart.
|
||||
*/
|
||||
const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
|
||||
/** A full document is 5,000 rows of well under 2 KB each. */
|
||||
const HEAD_LOOKUP_MAX_OUTPUT_BYTES = 16_000_000;
|
||||
const RATE_LIMIT_READING = "query { rateLimit { cost limit remaining resetAt } }";
|
||||
|
||||
class PullRequestsByHeadRead extends Request.Class<
|
||||
{
|
||||
readonly cwd: string;
|
||||
readonly host: string;
|
||||
readonly owner: string;
|
||||
readonly name: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: PullRequestListState;
|
||||
readonly limit: number;
|
||||
},
|
||||
ReadonlyArray<NormalizedGitHubPullRequestRecord>,
|
||||
GitHubCliError
|
||||
> {}
|
||||
|
||||
const GraphQlVariables = Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Union([Schema.String, Schema.Array(Schema.String)]),
|
||||
);
|
||||
/** A GraphQL request body for `gh api graphql --input -`. */
|
||||
const encodeGraphQlRequest = Schema.encodeSync(
|
||||
Schema.fromJsonString(Schema.Struct({ query: Schema.String, variables: GraphQlVariables })),
|
||||
);
|
||||
|
||||
/** One aliased `pullRequests` connection per lookup, each head and state passed as a variable. */
|
||||
function buildPullRequestsByHeadQuery(
|
||||
lookups: ReadonlyArray<Pick<PullRequestsByHeadRead, "headRefName" | "state" | "limit">>,
|
||||
): { readonly document: string; readonly variables: typeof GraphQlVariables.Type } {
|
||||
const variables: Record<string, string | ReadonlyArray<string>> = {};
|
||||
const declarations: string[] = ["$owner: String!", "$name: String!"];
|
||||
const selections: string[] = [];
|
||||
for (const [index, lookup] of lookups.entries()) {
|
||||
variables[`h${index}`] = lookup.headRefName;
|
||||
variables[`s${index}`] = GRAPHQL_STATES[lookup.state];
|
||||
declarations.push(`$h${index}: String!`, `$s${index}: [PullRequestState!]`);
|
||||
// `gh pr list` orders the same way, so a head with more matches than the limit keeps the
|
||||
// same rows.
|
||||
selections.push(
|
||||
` h${index}: pullRequests(headRefName: $h${index}, states: $s${index}, first: ${lookup.limit}, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { ${PULL_REQUEST_NODE_SELECTION} } }`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
document: `query PullRequestsByHead(${declarations.join(", ")}) {\n repository(owner: $owner, name: $name) {\n${selections.join("\n")}\n }\n}`,
|
||||
variables,
|
||||
};
|
||||
}
|
||||
|
||||
/** The reset time of a `rateLimit` reading, which sets when the next one is due. */
|
||||
const decodeRateLimitReading = (raw: string) =>
|
||||
Result.map(
|
||||
decodeJsonResult(
|
||||
Schema.Struct({
|
||||
data: Schema.Struct({ rateLimit: Schema.Struct({ resetAt: Schema.String }) }),
|
||||
}),
|
||||
)(raw),
|
||||
(reading) => reading.data.rateLimit.resetAt,
|
||||
);
|
||||
|
||||
const decodePullRequestsByHead = decodeJsonResult(
|
||||
Schema.Struct({
|
||||
data: Schema.Struct({
|
||||
repository: Schema.Record(
|
||||
Schema.String,
|
||||
Schema.NullOr(Schema.Struct({ nodes: Schema.Array(Schema.Unknown) })),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* The repository `gh pr list` reads in a checkout, picked the way gh picks one without a
|
||||
* prompt: the remote `gh repo set-default` marked, else the first of upstream, github, origin
|
||||
* (in any case), else the only remote. `remotes` is `git remote -v` output and `resolved` is the output of
|
||||
* `git config --get-regexp '^remote\..*\.gh-resolved$'`.
|
||||
*
|
||||
* Null whenever gh might weigh the remotes differently: a remote on another host or under an
|
||||
* SSH alias, more than one mark, or several remotes with none of those names. Callers then
|
||||
* ask gh itself.
|
||||
*/
|
||||
export function selectGitHubBaseRepository(input: {
|
||||
readonly remotes: string;
|
||||
readonly resolved: string;
|
||||
readonly host: string;
|
||||
}): { readonly owner: string; readonly name: string } | null {
|
||||
const host = input.host.toLowerCase();
|
||||
const repositories = new Map<string, { readonly owner: string; readonly name: string }>();
|
||||
for (const line of input.remotes.split("\n")) {
|
||||
const match = /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim());
|
||||
if (!match) continue;
|
||||
const [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(match[2]!).split("/");
|
||||
if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
|
||||
repositories.set(match[1]!, { owner, name });
|
||||
}
|
||||
const marks = input.resolved
|
||||
.split("\n")
|
||||
.map((line) => /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()))
|
||||
.filter((match): match is RegExpExecArray => match !== null && repositories.has(match[1]!));
|
||||
if (marks.length > 1) return null;
|
||||
const [mark] = marks;
|
||||
if (mark) {
|
||||
if (mark[2] === "base") return repositories.get(mark[1]!) ?? null;
|
||||
const [owner, name, ...rest] = mark[2]!.toLowerCase().split("/");
|
||||
return owner && name && rest.length === 0 ? { owner, name } : null;
|
||||
}
|
||||
// gh sorts remotes by these names, case-insensitively, and takes the first. A tie for the
|
||||
// top place has no defined winner.
|
||||
const score = (remoteName: string) =>
|
||||
["origin", "github", "upstream"].indexOf(remoteName.toLowerCase()) + 1;
|
||||
const ranked = [...repositories.entries()].toSorted(
|
||||
([left], [right]) => score(right) - score(left),
|
||||
);
|
||||
const [top, next] = ranked;
|
||||
return top !== undefined && (next === undefined || score(top[0]) > score(next[0]))
|
||||
? top[1]
|
||||
: null;
|
||||
}
|
||||
|
||||
/** @public Service construction is part of the canonical Effect module API. */
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
@@ -438,66 +601,86 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const quota = yield* Cache.makeWith(
|
||||
/**
|
||||
* A GraphQL `rateLimit` reading per host and credential, so the budget knows the balance
|
||||
* before reads that cannot report their own cost (`gh pr list`). GraphQL documents keep it
|
||||
* current in between. Each reading costs one point and is redone at the reset, or after ten
|
||||
* minutes so a `gh auth switch` is not priced against the old account for a whole hour.
|
||||
*/
|
||||
const budgetReading = yield* Cache.makeWith(
|
||||
(key: string) => {
|
||||
const host = key.split("\0")[0]!;
|
||||
return executeRaw({
|
||||
cwd: globalThis.process.cwd(),
|
||||
args: [
|
||||
"api",
|
||||
"rate_limit",
|
||||
"--hostname",
|
||||
host,
|
||||
"--jq",
|
||||
".resources.graphql | {data:{rateLimit:{cost:1,limit:.limit,remaining:.remaining,resetAt:(.reset|todateiso8601)}}}",
|
||||
],
|
||||
args: ["api", "graphql", "--hostname", host, "-f", `query=${RATE_LIMIT_READING}`],
|
||||
}).pipe(
|
||||
Effect.tap((result) => budget.observe(host, result.stdout)),
|
||||
Effect.asVoid,
|
||||
Effect.flatMap((result) =>
|
||||
Clock.currentTimeMillis.pipe(
|
||||
Effect.map((now) => {
|
||||
const resetAtMs = Date.parse(
|
||||
decodeRateLimitReading(result.stdout).pipe(
|
||||
Result.match({ onFailure: () => "", onSuccess: (reading) => reading }),
|
||||
),
|
||||
);
|
||||
// A reset that is missing or already past (a skewed clock) waits a minute, so a
|
||||
// bad reading cannot ask again on every read.
|
||||
return Duration.millis(
|
||||
Number.isFinite(resetAtMs) && resetAtMs > now
|
||||
? Math.min(resetAtMs - now, 600_000)
|
||||
: 60_000,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
{
|
||||
capacity: 32,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.seconds(30) : Duration.zero),
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? exit.value : Duration.minutes(1)),
|
||||
},
|
||||
);
|
||||
const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
|
||||
function* (input) {
|
||||
const [command, action] = input.args;
|
||||
if (
|
||||
!(
|
||||
(command === "pr" && (action === "list" || action === "view")) ||
|
||||
(command === "repo" && action === "view")
|
||||
)
|
||||
)
|
||||
return yield* executeRaw(input);
|
||||
|
||||
/**
|
||||
* Runs a GraphQL-priced read under its host's pause and the GraphQL budget. `run` receives
|
||||
* the document with `rateLimit` added, so a GraphQL read can report what it spent; a CLI read
|
||||
* ignores it and is priced at one point.
|
||||
*/
|
||||
const guardedRead = <A>(input: {
|
||||
readonly cwd: string;
|
||||
readonly host: string;
|
||||
readonly document: string;
|
||||
readonly allowReserve: boolean;
|
||||
readonly run: (document: string) => Effect.Effect<A, GitHubCliError>;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const credential = yield* PinnedGitHubCredential;
|
||||
if (credential !== null && !targetsVerifiedHost(input.args, credential.host))
|
||||
return yield* executeRaw(input);
|
||||
const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);
|
||||
const host = (
|
||||
credential?.host ??
|
||||
commandHosts(input.args).find((host) => host !== null) ??
|
||||
input.rateLimitHost ??
|
||||
input.env?.GH_HOST ??
|
||||
globalThis.process.env.GH_HOST ??
|
||||
"github.com"
|
||||
).toLowerCase();
|
||||
const key = { provider: "github" as const, host };
|
||||
const key = { provider: "github" as const, host: input.host };
|
||||
const guarded = Effect.gen(function* () {
|
||||
const lease = yield* limits.check(key, allowReserve ? { allowPaused: true } : undefined);
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* Cache.get(quota, `${host}\0${credential?.credentialFingerprint ?? ""}`);
|
||||
yield* budget.query(host, "query {}", allowReserve ? { allowReserve: true } : undefined);
|
||||
return yield* executeRaw(input);
|
||||
}).pipe(
|
||||
Effect.tap(() => limits.recordSuccess({ ...key, lease })),
|
||||
Effect.tapError((error) =>
|
||||
error._tag === "GitHubCliRateLimitError"
|
||||
? limits.recordRateLimit({ ...key, lease })
|
||||
: Effect.void,
|
||||
),
|
||||
const lease = yield* limits.check(
|
||||
key,
|
||||
input.allowReserve ? { allowPaused: true } : undefined,
|
||||
);
|
||||
// A failed reading leaves the budget unknown; it never blocks the read itself.
|
||||
yield* Cache.get(
|
||||
budgetReading,
|
||||
`${input.host}\0${yield* SourceControlRateLimit.CredentialScope}`,
|
||||
).pipe(Effect.ignore);
|
||||
return yield* budget
|
||||
.query(
|
||||
input.host,
|
||||
input.document,
|
||||
input.allowReserve ? { allowReserve: true } : undefined,
|
||||
)
|
||||
.pipe(
|
||||
Effect.flatMap(input.run),
|
||||
Effect.tap(() => limits.recordSuccess({ ...key, lease })),
|
||||
Effect.tapError((error) =>
|
||||
error._tag === "GitHubCliRateLimitError"
|
||||
? limits.recordRateLimit({ ...key, lease })
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
});
|
||||
return yield* guarded.pipe(
|
||||
Effect.provideService(
|
||||
@@ -516,11 +699,218 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
|
||||
function* (input) {
|
||||
const [command, action] = input.args;
|
||||
if (
|
||||
!(
|
||||
(command === "pr" && (action === "list" || action === "view")) ||
|
||||
(command === "repo" && action === "view")
|
||||
)
|
||||
)
|
||||
return yield* executeRaw(input);
|
||||
const credential = yield* PinnedGitHubCredential;
|
||||
if (credential !== null && !targetsVerifiedHost(input.args, credential.host))
|
||||
return yield* executeRaw(input);
|
||||
return yield* guardedRead({
|
||||
cwd: input.cwd,
|
||||
host: (
|
||||
credential?.host ??
|
||||
commandHosts(input.args).find((host) => host !== null) ??
|
||||
input.rateLimitHost ??
|
||||
input.env?.GH_HOST ??
|
||||
globalThis.process.env.GH_HOST ??
|
||||
"github.com"
|
||||
).toLowerCase(),
|
||||
document: "query {}",
|
||||
allowReserve: input.allowReserve ?? (yield* AllowGitHubReserve),
|
||||
run: () => executeRaw(input),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const listPullRequestsWithCli = (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly state: PullRequestListState;
|
||||
readonly limit: number;
|
||||
readonly rateLimitHost?: string | undefined;
|
||||
}) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headSelector,
|
||||
"--state",
|
||||
input.state,
|
||||
"--limit",
|
||||
String(input.limit),
|
||||
"--json",
|
||||
PULL_REQUEST_LIST_JSON_FIELDS,
|
||||
],
|
||||
}).pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const raw = result.stdout.trim();
|
||||
if (raw.length === 0) return Effect.succeed([]);
|
||||
const decoded = decodeGitHubPullRequestListJson(raw);
|
||||
return Result.isSuccess(decoded)
|
||||
? Effect.succeed(decoded.success)
|
||||
: Effect.fail(
|
||||
new GitHubChangeRequestListDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const git = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
process.run({
|
||||
operation: "GitHubCli.baseRepository",
|
||||
command: "git",
|
||||
args,
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
|
||||
/** The repository gh reads in `cwd`, or null when gh could pick it another way. */
|
||||
const resolveBaseRepository = (cwd: string, host: string) =>
|
||||
globalThis.process.env.GH_REPO
|
||||
? Effect.succeed(null)
|
||||
: Effect.all([
|
||||
git(cwd, ["remote", "-v"]),
|
||||
git(cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
|
||||
]).pipe(
|
||||
Effect.map(([remotes, resolved]) =>
|
||||
remotes.exitCode === 0
|
||||
? selectGitHubBaseRepository({
|
||||
remotes: remotes.stdout,
|
||||
resolved: resolved.exitCode === 0 ? resolved.stdout : "",
|
||||
host,
|
||||
})
|
||||
: null,
|
||||
),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
const headResolver = RequestResolver.makeGrouped<PullRequestsByHeadRead, string>({
|
||||
key: ({ request, context }) =>
|
||||
JSON.stringify([
|
||||
request.host,
|
||||
request.owner,
|
||||
request.name,
|
||||
Context.getOrElse(context, PinnedGitHubCredential, () => null)?.credentialFingerprint ??
|
||||
null,
|
||||
Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
|
||||
]),
|
||||
resolver: (entries) => {
|
||||
const [first] = entries;
|
||||
const { cwd, host, owner, name } = first.request;
|
||||
const query = buildPullRequestsByHeadQuery(entries.map((entry) => entry.request));
|
||||
const readCli = (entry: (typeof entries)[number]) =>
|
||||
listPullRequestsWithCli({
|
||||
cwd: entry.request.cwd,
|
||||
headSelector: entry.request.headRefName,
|
||||
state: entry.request.state,
|
||||
limit: entry.request.limit,
|
||||
rateLimitHost: entry.request.host,
|
||||
}).pipe(
|
||||
Effect.exit,
|
||||
Effect.map((exit) => entry.completeUnsafe(exit)),
|
||||
);
|
||||
return guardedRead({
|
||||
cwd,
|
||||
host,
|
||||
document: query.document,
|
||||
allowReserve: false,
|
||||
run: (document) =>
|
||||
executeRaw({
|
||||
cwd,
|
||||
args: ["api", "graphql", "--hostname", host, "--input", "-"],
|
||||
// Up to 50 heads of 100 rows each. A default branch such as `main` can match a
|
||||
// hundred fork pull requests, so the 1 MB default would cut the answer short.
|
||||
maxOutputBytes: HEAD_LOOKUP_MAX_OUTPUT_BYTES,
|
||||
stdin: encodeGraphQlRequest({
|
||||
query: document,
|
||||
variables: { owner, name, ...query.variables },
|
||||
}),
|
||||
}).pipe(Effect.tap((result) => budget.observe(host, result.stdout))),
|
||||
}).pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const decoded = decodePullRequestsByHead(result.stdout);
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.forEach(entries, readCli, { discard: true });
|
||||
}
|
||||
const aliases = decoded.success.data.repository;
|
||||
return Effect.forEach(
|
||||
entries,
|
||||
(entry, index) => {
|
||||
const alias = aliases[`h${index}`];
|
||||
if (alias == null) return readCli(entry);
|
||||
entry.completeUnsafe(Exit.succeed(decodeGitHubPullRequestEntries(alias.nodes)));
|
||||
return Effect.void;
|
||||
},
|
||||
{ discard: true },
|
||||
);
|
||||
}),
|
||||
// A document GitHub refused as a whole (a renamed repository, a field an older
|
||||
// Enterprise host lacks) leaves each lookup to gh. A rate limit fails them all:
|
||||
// asking one at a time would only spend what the pause is saving.
|
||||
Effect.catchIf(
|
||||
(error) => error._tag !== "GitHubCliRateLimitError",
|
||||
() => Effect.forEach(entries, readCli, { discard: true }),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.sync(() => {
|
||||
for (const entry of entries) entry.completeUnsafe(Exit.failCause(cause));
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
}).pipe(
|
||||
RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
|
||||
RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT),
|
||||
);
|
||||
|
||||
const listPullRequestsByHead: GitHubCli["Service"]["listPullRequestsByHead"] = Effect.fn(
|
||||
"GitHubCli.listPullRequestsByHead",
|
||||
)(function* (input) {
|
||||
const host = input.rateLimitHost?.toLowerCase();
|
||||
const credential = yield* PinnedGitHubCredential;
|
||||
// `owner:branch` selectors and other hosts keep gh's own handling.
|
||||
const repository =
|
||||
host === undefined ||
|
||||
input.headSelector.includes(":") ||
|
||||
(credential !== null && credential.host !== host)
|
||||
? null
|
||||
: yield* resolveBaseRepository(input.cwd, host);
|
||||
if (host === undefined || repository === null) {
|
||||
return yield* listPullRequestsWithCli(input);
|
||||
}
|
||||
return yield* Effect.request(
|
||||
new PullRequestsByHeadRead({
|
||||
cwd: input.cwd,
|
||||
host,
|
||||
owner: repository.owner,
|
||||
name: repository.name,
|
||||
headRefName: input.headSelector,
|
||||
state: input.state,
|
||||
limit: Math.min(Math.max(Math.trunc(input.limit), 1), 100),
|
||||
}),
|
||||
headResolver,
|
||||
);
|
||||
});
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
listPullRequestsByHead,
|
||||
listOpenPullRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
|
||||
import { parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
|
||||
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
|
||||
|
||||
@@ -32,19 +33,13 @@ function makeProvider(github: Partial<GitHubCli.GitHubCli["Service"]>) {
|
||||
|
||||
it.effect("uses the enterprise quota for a current-repository default branch read", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* GitHubSourceControlProvider.make.pipe(
|
||||
Effect.provide(GitHubCli.layer),
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.args[1] !== "rate_limit") return processResult("main");
|
||||
assert.strictEqual(input.args[3], "enterprise.test");
|
||||
return processResult(
|
||||
'{"data":{"rateLimit":{"cost":1,"limit":5000,"remaining":5000,"resetAt":"2099-01-01T00:00:00Z"}}}',
|
||||
);
|
||||
}),
|
||||
}),
|
||||
// github.com is out of quota; the enterprise read must not be priced against it.
|
||||
const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
|
||||
yield* budget.observe(
|
||||
"github.com",
|
||||
'{"data":{"rateLimit":{"cost":1,"limit":5000,"remaining":0,"resetAt":"2099-01-01T00:00:00Z"}}}',
|
||||
);
|
||||
const provider = yield* GitHubSourceControlProvider.make;
|
||||
const branch = yield* provider.getDefaultBranch({
|
||||
cwd: "/enterprise-repo",
|
||||
context: {
|
||||
@@ -54,7 +49,12 @@ it.effect("uses the enterprise quota for a current-repository default branch rea
|
||||
},
|
||||
});
|
||||
assert.strictEqual(branch, "main");
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.provide(GitHubCli.layer),
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: () => Effect.succeed(processResult("main")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
|
||||
@@ -138,50 +138,47 @@ it.effect("adds safe request context while retaining GitHub CLI causes", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses gh json listing for non-open change request state queries", () =>
|
||||
it.effect("lists change request history through the batched head lookup", () =>
|
||||
Effect.gen(function* () {
|
||||
let executeArgs: ReadonlyArray<string> = [];
|
||||
let lookup: Parameters<GitHubCli.GitHubCli["Service"]["listPullRequestsByHead"]>[0] | null =
|
||||
null;
|
||||
const provider = yield* makeProvider({
|
||||
execute: (input) => {
|
||||
executeArgs = input.args;
|
||||
return Effect.succeed(
|
||||
processResult(
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 7,
|
||||
title: "Merged work",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/7",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/merged",
|
||||
state: "merged",
|
||||
mergedAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
listPullRequestsByHead: (input) => {
|
||||
lookup = input;
|
||||
return Effect.succeed([
|
||||
{
|
||||
number: 7,
|
||||
title: "Merged work",
|
||||
url: "https://enterprise.test/acme/web/pull/7",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/merged",
|
||||
state: "merged",
|
||||
mergedAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
|
||||
},
|
||||
]);
|
||||
},
|
||||
});
|
||||
|
||||
const changeRequests = yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
context: {
|
||||
provider: { kind: "github", name: "GitHub Enterprise", baseUrl: "https://enterprise.test" },
|
||||
remoteName: "origin",
|
||||
remoteUrl: "https://enterprise.test/acme/web.git",
|
||||
},
|
||||
headSelector: "feature/merged",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(executeArgs, [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
"feature/merged",
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"10",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
]);
|
||||
assert.deepStrictEqual(lookup, {
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/merged",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
rateLimitHost: "enterprise.test",
|
||||
});
|
||||
assert.strictEqual(changeRequests[0]?.provider, "github");
|
||||
assert.strictEqual(changeRequests[0]?.state, "merged");
|
||||
assert.strictEqual(changeRequests[0]?.mergedAt, "2026-01-01T00:00:00Z");
|
||||
@@ -192,23 +189,6 @@ it.effect("uses gh json listing for non-open change request state queries", () =
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("treats empty non-open change request listing output as no results", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
execute: () => Effect.succeed(processResult("")),
|
||||
});
|
||||
|
||||
const changeRequests = yield* provider.listChangeRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/empty",
|
||||
state: "all",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(changeRequests, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates GitHub PRs through provider-neutral input names", () =>
|
||||
Effect.gen(function* () {
|
||||
let createInput: Parameters<GitHubCli.GitHubCli["Service"]["createPullRequest"]>[0] | null =
|
||||
|
||||
@@ -2,16 +2,10 @@ import * as Schema from "effect/Schema";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import {
|
||||
SourceControlProviderError,
|
||||
type ChangeRequest,
|
||||
type ChangeRequestState,
|
||||
} from "@t3tools/contracts";
|
||||
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
import { findAuthenticatedGitHubAccount, parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";
|
||||
import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
|
||||
import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
import {
|
||||
combinedAuthOutput,
|
||||
@@ -151,59 +145,28 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
const stateArg: ChangeRequestState | "all" = input.state;
|
||||
return github
|
||||
.execute({
|
||||
.listPullRequestsByHead({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
state: input.state,
|
||||
limit: input.limit ?? 20,
|
||||
...(input.context === undefined
|
||||
? {}
|
||||
: { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headSelector,
|
||||
"--state",
|
||||
stateArg,
|
||||
"--limit",
|
||||
String(input.limit ?? 20),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,isDraft,mergedAt,closedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((result) => {
|
||||
const raw = result.stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return Effect.succeed([]);
|
||||
}
|
||||
return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) =>
|
||||
Result.isSuccess(decoded)
|
||||
? Effect.succeed(
|
||||
decoded.success.map((item) => {
|
||||
const { updatedAt, ...summary } = item;
|
||||
return {
|
||||
...toChangeRequest({
|
||||
...summary,
|
||||
...(Option.isSome(updatedAt)
|
||||
? { updatedAt: DateTime.formatIso(updatedAt.value) }
|
||||
: {}),
|
||||
}),
|
||||
updatedAt,
|
||||
};
|
||||
}),
|
||||
)
|
||||
: Effect.fail(
|
||||
new GitHubCli.GitHubChangeRequestListDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.map((items) =>
|
||||
items.map(({ updatedAt, ...summary }) => ({
|
||||
...toChangeRequest({
|
||||
...summary,
|
||||
...(Option.isSome(updatedAt)
|
||||
? { updatedAt: DateTime.formatIso(updatedAt.value) }
|
||||
: {}),
|
||||
}),
|
||||
updatedAt,
|
||||
})),
|
||||
),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
|
||||
@@ -114,25 +114,30 @@ const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown
|
||||
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
|
||||
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
|
||||
|
||||
/**
|
||||
* Pull request rows in `gh --json` or GraphQL node shape. A row that does not decode is
|
||||
* skipped, so one malformed pull request cannot hide the rest.
|
||||
*/
|
||||
export function decodeGitHubPullRequestEntries(
|
||||
entries: ReadonlyArray<unknown>,
|
||||
): ReadonlyArray<NormalizedGitHubPullRequestRecord> {
|
||||
const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
|
||||
for (const entry of entries) {
|
||||
const decodedEntry = decodeGitHubPullRequestEntry(entry);
|
||||
if (Exit.isSuccess(decodedEntry)) {
|
||||
pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
|
||||
}
|
||||
}
|
||||
return pullRequests;
|
||||
}
|
||||
|
||||
export function decodeGitHubPullRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitHubPullRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitHubPullRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitHubPullRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(pullRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
return Result.map(decodeGitHubPullRequestList(raw), decodeGitHubPullRequestEntries);
|
||||
}
|
||||
|
||||
export function decodeGitHubPullRequestJson(
|
||||
|
||||
@@ -747,6 +747,8 @@ export const PullRequestSummary = Schema.Struct({
|
||||
reviewDecision: Schema.optional(Schema.NullOr(PullRequestReviewDecision)),
|
||||
checksState: Schema.optional(Schema.NullOr(PullRequestChecksState)),
|
||||
mergeability: Schema.optional(PullRequestMergeability),
|
||||
/** Null when the host says the pull request is in no stack; absent when the read did not ask. */
|
||||
stack: Schema.optional(Schema.NullOr(PullRequestStackMembership)),
|
||||
});
|
||||
export type PullRequestSummary = typeof PullRequestSummary.Type;
|
||||
|
||||
|
||||
Reference in new issue
Block a user