refactor(source-control): GitHub lives in @t3tools/source-control-github (#17607)

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-09 14:50:02 -07:00
1 parent 8d1858d9d6
commit 507361bc73
51 files changed
+411 -195

No files matched your search

@@ -0,0 +1,525 @@
import { describe, expect, it } from "@effect/vitest";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as PlatformError from "effect/PlatformError";
import * as TestClock from "effect/testing/TestClock";
import * as Tracer from "effect/Tracer";
import { ChildProcessSpawner } from "effect/process";
import { VcsProcessSpawnError, VcsProcessTimeoutError } from "@t3tools/contracts";
import { HttpClient, HttpClientResponse, type HttpClientRequest } from "effect/http";
import * as GitHubApi from "./GitHubApi.ts";
import * as GitHubCredentials from "./GitHubCredentials.ts";
import * as GitHubQuota from "./GitHubQuota.ts";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
const NOW = Date.parse("2026-10-05T12:00:00.000Z");
function harness(respond: (request: HttpClientRequest.HttpClientRequest) => Response) {
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
let tokens = ["first", "second"];
let invalidations = 0;
const credentials = Layer.succeed(
GitHubCredentials.GitHubCredentials,
GitHubCredentials.GitHubCredentials.of({
get: (host) =>
Effect.sync(() => ({
host,
token: Redacted.make(tokens[0]!),
source: "gh" as const,
fingerprint: `${host}:${tokens[0]}`,
})),
invalidate: () =>
Effect.sync(() => {
invalidations++;
tokens = tokens.slice(1);
}),
}),
);
const http = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => {
requests.push(request);
return Effect.succeed(HttpClientResponse.fromWeb(request, respond(request)));
}),
);
const layer = GitHubApi.layer.pipe(
Layer.provide(Layer.mergeAll(credentials, http)),
Layer.provideMerge(GitHubQuota.layer),
Layer.provideMerge(SourceControlRateLimit.layer),
);
return { layer, requests, invalidations: () => invalidations };
}
const json = (body: unknown, init?: ResponseInit) =>
new Response(JSON.stringify(body), {
...init,
headers: { "content-type": "application/json", ...init?.headers },
});
describe("gitHubApiUrls", () => {
it("maps github.com, GHE.com and GitHub Enterprise Server", () => {
expect(GitHubApi.gitHubApiUrls("GitHub.com")).toEqual({
rest: "https://api.github.com",
graphql: "https://api.github.com/graphql",
});
expect(GitHubApi.gitHubApiUrls("acme.ghe.com").graphql).toBe(
"https://api.acme.ghe.com/graphql",
);
expect(GitHubApi.gitHubApiUrls("git.acme.internal")).toEqual({
rest: "https://git.acme.internal/api/v3",
graphql: "https://git.acme.internal/api/graphql",
});
});
});
describe("environmentToken", () => {
it("follows gh's precedence per kind of host", () => {
const env = { GH_TOKEN: "gh", GITHUB_TOKEN: "github", GH_ENTERPRISE_TOKEN: "ghe" };
expect(GitHubCredentials.environmentToken("github.com", env)).toBe("gh");
expect(GitHubCredentials.environmentToken("acme.ghe.com", { GITHUB_TOKEN: "github" })).toBe(
"github",
);
// An enterprise token only goes to the host GH_HOST names, never to whatever a remote says.
expect(GitHubCredentials.environmentToken("git.acme.internal", env)).toBeNull();
expect(
GitHubCredentials.environmentToken("git.acme.internal", {
...env,
GH_HOST: "git.acme.internal",
}),
).toBe("ghe");
expect(GitHubCredentials.environmentToken("git.acme.internal", { GH_TOKEN: "gh" })).toBeNull();
});
});
describe("GitHubApi", () => {
it.effect("sends GraphQL with the token, and the document as written", () => {
const { layer, requests } = harness(() => json({ data: { viewer: { login: "julius" } } }));
return Effect.gen(function* () {
yield* TestClock.setTime(NOW);
const api = yield* GitHubApi.GitHubApi;
const body = yield* api.graphql({
host: "github.com",
operation: "viewer",
query: "query { viewer { login } }",
});
expect(body).toContain('"login":"julius"');
expect(requests[0]!.url).toBe("https://api.github.com/graphql");
expect(requests[0]!.headers.authorization).toBe("Bearer first");
// No `rateLimit` selection is added: the quota is read off the response headers.
const sent = requests[0]!.body;
expect(sent._tag === "Uint8Array" ? new TextDecoder().decode(sent.body) : "").toContain(
'"query":"query { viewer { login } }"',
);
}).pipe(Effect.provide(layer));
});
it.effect(
"traces the operation, path, query and quota, never the query string or variables",
() => {
const spans: Array<Tracer.NativeSpan> = [];
const tracer = Tracer.make({
span: (options) => {
const span = new Tracer.NativeSpan(options);
spans.push(span);
return span;
},
});
const { layer } = harness((request) =>
request.url.endsWith("/graphql")
? json(
{ data: { viewer: { login: "julius" } } },
{ headers: { "x-ratelimit-remaining": "4990", "x-ratelimit-resource": "graphql" } },
)
: json({ ok: true }, { headers: { "x-ratelimit-remaining": "4800" } }),
);
return Effect.gen(function* () {
yield* TestClock.setTime(NOW);
const api = yield* GitHubApi.GitHubApi;
yield* api.graphql({
host: "github.com",
operation: "getPullRequestDetail",
query: "query($body: String!) { viewer { login } }",
variables: { body: "secret user text" },
});
yield* api.rest({
host: "github.com",
operation: "listWorkflowRuns",
path: "repos/acme/web/actions/runs?head_sha=abc123&branch=feat%2Fx",
});
const byName = (name: string) => spans.filter((span) => span.name === name);
const graphql = Object.fromEntries(byName("GitHubApi.graphql")[0]!.attributes);
expect(graphql).toMatchObject({
"github.operation": "getPullRequestDetail",
"github.graphql.query": "query($body: String!) { viewer { login } }",
});
expect(Object.fromEntries(byName("GitHubApi.send")[0]!.attributes)).toMatchObject({
"github.ratelimit.remaining": 4990,
"github.ratelimit.resource": "graphql",
});
expect(String(graphql["github.graphql.query_hash"])).toMatch(/^[0-9a-f]{8}$/);
const rest = Object.fromEntries(byName("GitHubApi.send")[1]!.attributes);
expect(rest).toMatchObject({
"github.operation": "listWorkflowRuns",
"github.kind": "rest",
"url.path": "/repos/acme/web/actions/runs",
"http.response.status_code": 200,
"github.ratelimit.remaining": 4800,
});
// Nothing recorded carries the query string, the variables, or the token.
const everything = spans
.flatMap((span) => [...span.attributes].map(([key, value]) => `${key}=${String(value)}`))
.join("\n");
expect(everything).not.toContain("head_sha");
expect(everything).not.toContain("secret user text");
expect(everything).not.toContain("first");
expect(spans.some((span) => span.attributes.has("url.full"))).toBe(false);
}).pipe(Effect.provide(layer), Effect.withTracer(tracer));
},
);
it.effect("fails a GraphQL answer that carries errors, naming GitHub's reason", () => {
const { layer } = harness(() =>
json({ data: null, errors: [{ type: "FORBIDDEN", message: "Resource not accessible" }] }),
);
return Effect.gen(function* () {
const api = yield* GitHubApi.GitHubApi;
const error = yield* Effect.flip(
api.graphql({ host: "github.com", operation: "detail", query: "query { viewer { id } }" }),
);
expect(error._tag).toBe("GitHubApiResponseError");
expect(error.message).toContain("Resource not accessible");
}).pipe(Effect.provide(layer));
});
it.effect(
"reads a NOT_FOUND answer with another error as a failure, not a missing resource",
() => {
const { layer } = harness(() =>
json({
data: null,
errors: [
{ type: "NOT_FOUND", message: "Could not resolve" },
{ message: "Something went wrong" },
],
}),
);
return Effect.gen(function* () {
const api = yield* GitHubApi.GitHubApi;
const error = yield* Effect.flip(
api.graphql({
host: "github.com",
operation: "detail",
query: "query { viewer { id } }",
}),
);
expect(error._tag).toBe("GitHubApiResponseError");
}).pipe(Effect.provide(layer));
},
);
it.effect("pauses the host after a GraphQL RATE_LIMITED answer until the reset", () => {
const reset = Math.floor(NOW / 1000) + 600;
const { layer, requests } = harness(() =>
json(
{ errors: [{ type: "RATE_LIMITED", message: "API rate limit exceeded" }] },
{ headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
),
);
return Effect.gen(function* () {
yield* TestClock.setTime(NOW);
const api = yield* GitHubApi.GitHubApi;
const first = yield* Effect.flip(
api.graphql({ host: "github.com", operation: "summary", query: "query { viewer { id } }" }),
);
expect(first).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
const second = yield* Effect.flip(
api.rest({ host: "github.com", operation: "stack", path: "repos/acme/web/stacks" }),
);
expect(second).toMatchObject({
_tag: "SourceControlRateLimitPausedError",
retryAt: reset * 1000,
});
expect(requests).toHaveLength(1);
}).pipe(Effect.provide(layer));
});
it.effect("keeps the last tenth of a quota for interactive requests until it resets", () => {
const reset = Math.floor(NOW / 1000) + 600;
const quota = (remaining: number) => ({
"x-ratelimit-resource": "core",
"x-ratelimit-limit": "5000",
"x-ratelimit-remaining": String(remaining),
"x-ratelimit-reset": String(reset),
});
let remaining = 499;
const { layer, requests } = harness((request) =>
request.url.endsWith("/graphql")
? json({ data: { viewer: { id: "1" } } })
: json({ ok: true }, { headers: quota(remaining--) }),
);
return Effect.gen(function* () {
yield* TestClock.setTime(NOW);
const api = yield* GitHubApi.GitHubApi;
const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
// The first answer leaves 499 of 5000, under the last tenth; the next background read waits.
yield* api.rest(read);
const refused = yield* Effect.flip(api.rest(read));
expect(refused).toMatchObject({
_tag: "SourceControlRateLimitPausedError",
retryAt: reset * 1000,
});
// A user's own request may spend the reserve, and GraphQL has a quota of its own.
yield* api.rest(read).pipe(Effect.provideService(GitHubApi.AllowGitHubReserve, true));
yield* api.graphql({ host: "github.com", operation: "x", query: "query { viewer { id } }" });
expect(requests).toHaveLength(3);
// The reset gives the background its quota back.
yield* TestClock.setTime(reset * 1000);
yield* api.rest(read);
expect(requests).toHaveLength(4);
}).pipe(Effect.provide(layer));
});
it.effect("carries GitHub's own reason for a refused REST request", () => {
const { layer } = harness(() =>
json(
{
message: "Validation Failed",
errors: [
{
resource: "PullRequest",
code: "custom",
message: "A pull request already exists for acme:feature.",
},
],
},
{ status: 422 },
),
);
return Effect.gen(function* () {
const api = yield* GitHubApi.GitHubApi;
const error = yield* Effect.flip(
api.rest({
host: "github.com",
operation: "createPullRequest",
method: "POST",
path: "repos/acme/web/pulls",
}),
);
expect(error.message).toBe(
"GitHub returned an error: Validation Failed; A pull request already exists for acme:feature.",
);
}).pipe(Effect.provide(layer));
});
it.effect("lets an interactive request through a pause a background read recorded", () => {
const reset = Math.floor(NOW / 1000) + 600;
let call = 0;
const { layer, requests } = harness(() =>
++call === 1
? json(
{ message: "API rate limit exceeded" },
{
status: 403,
headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) },
},
)
: json({ ok: true }),
);
return Effect.gen(function* () {
yield* TestClock.setTime(NOW);
const api = yield* GitHubApi.GitHubApi;
const read = { host: "github.com", operation: "sweep", path: "repos/acme/web/pulls" };
yield* Effect.flip(api.rest(read));
expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError");
const merged = yield* api
.rest({
host: "github.com",
operation: "merge",
method: "PUT",
path: "repos/acme/web/pulls/7/merge",
})
.pipe(Effect.provideService(GitHubApi.AllowGitHubReserve, true));
expect(merged.status).toBe(200);
expect(requests).toHaveLength(2);
}).pipe(Effect.provide(layer));
});
it.effect("reads an untyped GraphQL quota error as a rate limit", () => {
const reset = Math.floor(NOW / 1000) + 900;
const { layer } = harness(() =>
json(
{ errors: [{ message: "API rate limit already exceeded for user ID 1." }] },
{ headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(reset) } },
),
);
return Effect.gen(function* () {
yield* TestClock.setTime(NOW);
const api = yield* GitHubApi.GitHubApi;
const error = yield* Effect.flip(
api.graphql({ host: "github.com", operation: "lookup", query: "query { viewer { id } }" }),
);
expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: reset * 1000 });
}).pipe(Effect.provide(layer));
});
it.effect("maps REST 403 with an exhausted quota to a rate limit, and 304 to an answer", () => {
let call = 0;
const { layer } = harness(() =>
++call === 1
? new Response(null, { status: 304 })
: json(
{ message: "API rate limit exceeded" },
{
status: 403,
headers: { "retry-after": "60" },
},
),
);
return Effect.gen(function* () {
yield* TestClock.setTime(NOW);
const api = yield* GitHubApi.GitHubApi;
const notModified = yield* api.rest({
host: "github.com",
operation: "checks",
path: "repos/acme/web/pulls/7",
ifNoneMatch: '"abc"',
});
expect(notModified.status).toBe(304);
const error = yield* Effect.flip(
api.rest({ host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }),
);
expect(error).toMatchObject({ _tag: "GitHubApiRateLimitError", retryAt: NOW + 60_000 });
}).pipe(Effect.provide(layer));
});
it.effect("drops a refused token so the next request asks the source again", () => {
const { layer, requests, invalidations } = harness((request) =>
request.headers.authorization === "Bearer first"
? new Response(null, { status: 401 })
: json({ ok: true }),
);
return Effect.gen(function* () {
const api = yield* GitHubApi.GitHubApi;
const refused = yield* Effect.flip(
api.rest({ host: "github.com", operation: "user", path: "user" }),
);
expect(refused._tag).toBe("GitHubApiAuthenticationError");
expect(invalidations()).toBe(1);
const answered = yield* api.rest({ host: "github.com", operation: "user", path: "user" });
expect(answered.status).toBe(200);
expect(requests.map((request) => request.headers.authorization)).toEqual([
"Bearer first",
"Bearer second",
]);
}).pipe(Effect.provide(layer));
});
it.effect("refuses to send a pinned credential to another host", () => {
const { layer, requests } = harness(() => json({}));
return Effect.gen(function* () {
const api = yield* GitHubApi.GitHubApi;
const error = yield* Effect.flip(
api.rest({ host: "git.acme.internal", operation: "user", path: "user" }),
).pipe(
Effect.provideService(GitHubApi.PinnedGitHubCredential, {
host: "github.com",
token: Redacted.make("pinned"),
credentialFingerprint: "github.com:pinned",
}),
);
expect(error._tag).toBe("GitHubApiAuthenticationError");
expect(requests).toHaveLength(0);
}).pipe(Effect.provide(layer));
});
});
describe("GitHubCredentials", () => {
const credentialsWith = (run: SourceControlHost.SourceControlHost["Service"]["process"]["run"]) =>
GitHubCredentials.layer.pipe(
Layer.provide(TestSourceControlHost.layer({ process: { run } })),
Layer.provide(NodeCrypto.layer),
);
it.effect("fails with GitHubCliMissingError when gh is not on PATH", () =>
Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const error = yield* Effect.flip(credentials.get("git.acme.internal"));
expect(error._tag).toBe("GitHubCliMissingError");
}).pipe(
Effect.provide(
credentialsWith(() =>
Effect.fail(
new VcsProcessSpawnError({
operation: "GitHubCredentials.get",
command: "gh",
cwd: "/",
cause: PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
}),
}),
),
),
),
),
);
it.effect("does not cache a gh failure that is not about signing in", () => {
let calls = 0;
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const first = yield* Effect.flip(credentials.get("github.com"));
expect(first._tag).toBe("GitHubCliFailedError");
expect((yield* credentials.get("github.com")).source).toBe("gh");
expect(calls).toBe(2);
}).pipe(
Effect.provide(
credentialsWith(() =>
++calls === 1
? Effect.fail(
new VcsProcessTimeoutError({
operation: "GitHubCredentials.get",
command: "gh",
cwd: "/",
timeoutMs: 10_000,
}),
)
: Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "token\n",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}),
),
),
);
});
it.effect("fails with GitHubNotSignedInError when gh prints no token", () =>
Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const error = yield* Effect.flip(credentials.get("git.acme.internal"));
expect(error._tag).toBe("GitHubNotSignedInError");
}).pipe(
Effect.provide(
credentialsWith(() =>
Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "\n",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}),
),
),
),
);
});
@@ -0,0 +1,600 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http";
import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
import * as GitHubCredentials from "./GitHubCredentials.ts";
import * as GitHubQuota from "./GitHubQuota.ts";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
const DEFAULT_TIMEOUT = Duration.seconds(30);
const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
/** Polite to GitHub's secondary limits, which punish bursts of concurrent requests. */
const CONCURRENCY = 8;
const API_VERSION = "2022-11-28";
/**
* A credential already verified for one host. Every request made under it must target that
* host, so a page cannot read one account's data with another's token mid-flight. Server-local:
* never put its value in RPC payloads or cache keys.
*/
export const PinnedGitHubCredential = Context.Reference<{
readonly host: string;
readonly token: Redacted.Redacted<string>;
readonly credentialFingerprint: string;
} | null>("@t3tools/source-control-github/server/GitHubApi/PinnedGitHubCredential", {
defaultValue: () => null,
});
/**
* Set by interactive callers (a user's read or write, not a background sweep). Requests made
* under it may spend the GraphQL reserve and go through a rate-limit pause: a user acting on a
* pull request should not be refused because a background read exhausted the quota.
*/
export const AllowGitHubReserve = Context.Reference<boolean>(
"@t3tools/source-control-github/server/GitHubApi/AllowGitHubReserve",
{ defaultValue: () => false },
);
export class GitHubApiRequestError extends Schema.TaggedError<GitHubApiRequestError>()(
"GitHubApiRequestError",
{ host: Schema.String, operation: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `Could not reach GitHub at ${this.host}.`;
}
}
export class GitHubApiAuthenticationError extends Schema.TaggedError<GitHubApiAuthenticationError>()(
"GitHubApiAuthenticationError",
{ host: Schema.String, operation: Schema.String },
) {
override get message(): string {
return `GitHub refused the credential for ${this.host}. Run \`gh auth login --hostname ${this.host}\` and retry.`;
}
}
export class GitHubApiRateLimitError extends Schema.TaggedError<GitHubApiRateLimitError>()(
"GitHubApiRateLimitError",
{
host: Schema.String,
operation: Schema.String,
retryAt: Schema.optionalKey(Schema.Finite),
},
) {
override get message(): string {
return "GitHub API rate limit exceeded.";
}
}
export class GitHubApiNotFoundError extends Schema.TaggedError<GitHubApiNotFoundError>()(
"GitHubApiNotFoundError",
{ host: Schema.String, operation: Schema.String },
) {
override get message(): string {
return "GitHub could not find the requested resource, or the credential cannot see it.";
}
}
/**
* GitHub answered with a failure that is none of the above. `githubErrors` carries GitHub's own
* error messages, from a GraphQL `errors` list or a REST `message`/`errors` body: they name the
* field and the reason ("A pull request already exists for acme:feature"), never a token.
*/
export class GitHubApiResponseError extends Schema.TaggedError<GitHubApiResponseError>()(
"GitHubApiResponseError",
{
host: Schema.String,
operation: Schema.String,
status: Schema.Int,
githubErrors: Schema.optionalKey(Schema.Array(Schema.String)),
},
) {
override get message(): string {
return this.githubErrors !== undefined && this.githubErrors.length > 0
? `GitHub returned an error: ${this.githubErrors.join("; ")}`
: `GitHub returned HTTP ${this.status}.`;
}
}
export type GitHubApiError =
| GitHubCredentials.GitHubCredentialUnavailableError
| GitHubApiRequestError
| GitHubApiAuthenticationError
| GitHubApiRateLimitError
| GitHubApiNotFoundError
| GitHubApiResponseError
| SourceControlRateLimit.SourceControlRateLimitPausedError;
export interface GitHubRestResponse {
readonly status: number;
readonly headers: Readonly<Record<string, string | undefined>>;
readonly body: string;
readonly truncated: boolean;
/** The body was not valid UTF-8, which a raw file read takes to mean binary. */
readonly invalidUtf8: boolean;
}
export interface GitHubRestInput {
readonly host: string;
readonly operation: string;
readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
/** Relative to the API root, e.g. `repos/acme/web/pulls/7`; query string included. */
readonly path: string;
readonly body?: unknown;
/** Defaults to `application/vnd.github+json`. */
readonly accept?: string;
/** Revalidates a cached answer. A 304 is returned rather than failed, and is free. */
readonly ifNoneMatch?: string;
readonly maxResponseBytes?: number;
/** Defaults to 30 seconds; a whole pull request's patch may need longer. */
readonly timeout?: Duration.Input;
/** Overrides `AllowGitHubReserve` for this one request. */
readonly allowReserve?: boolean;
}
export interface GitHubGraphQlInput {
readonly host: string;
readonly operation: string;
readonly query: string;
readonly variables?: Readonly<Record<string, unknown>>;
readonly allowReserve?: boolean;
readonly maxResponseBytes?: number;
}
export class GitHubApi extends Context.Service<
GitHubApi,
{
/** The raw JSON body of a successful GraphQL answer, with `rateLimit` recorded. */
readonly graphql: (input: GitHubGraphQlInput) => Effect.Effect<string, GitHubApiError>;
readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
/** The credential a request to `host` would carry right now. */
readonly credential: (
host: string,
) => Effect.Effect<
{ readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
GitHubApiError
>;
}
>()("@t3tools/source-control-github/server/GitHubApi") {}
function normalizeHost(host: string): string {
return host.trim().toLowerCase();
}
/**
* Where the API for a host lives. github.com and GHE.com data residency serve it from an `api.`
* subdomain; GitHub Enterprise Server serves it under `/api` on the instance itself.
*/
export function gitHubApiUrls(host: string): { readonly rest: string; readonly graphql: string } {
const normalized = normalizeHost(host);
if (normalized === "github.com") {
return { rest: "https://api.github.com", graphql: "https://api.github.com/graphql" };
}
if (normalized.endsWith(".ghe.com")) {
return {
rest: `https://api.${normalized}`,
graphql: `https://api.${normalized}/graphql`,
};
}
return { rest: `https://${normalized}/api/v3`, graphql: `https://${normalized}/api/graphql` };
}
/** GraphQL documents longer than this are cut in traces; the hash still identifies them. */
const TRACED_QUERY_MAX_CHARS = 4_000;
/** A stable short id for a GraphQL document, so traces group by query without its text. */
function queryHash(query: string): string {
let hash = 0x811c9dc5;
for (let index = 0; index < query.length; index++) {
hash ^= query.charCodeAt(index);
hash = Math.imul(hash, 0x01000193);
}
return (hash >>> 0).toString(16).padStart(8, "0");
}
/** The numeric rate-limit headers GitHub sends, as span attributes. */
function rateLimitAttributes(
headers: Readonly<Record<string, string | undefined>>,
): Record<string, number | string> {
const attributes: Record<string, number | string> = {};
for (const [header, name] of [
["x-ratelimit-limit", "github.ratelimit.limit"],
["x-ratelimit-remaining", "github.ratelimit.remaining"],
["x-ratelimit-used", "github.ratelimit.used"],
["x-ratelimit-reset", "github.ratelimit.reset"],
] as const) {
const value = Number(headers[header]);
if (headers[header] !== undefined && Number.isFinite(value)) attributes[name] = value;
}
const resource = headers["x-ratelimit-resource"];
if (resource !== undefined) attributes["github.ratelimit.resource"] = resource;
return attributes;
}
/** The pause GitHub asked for, from `retry-after` or the primary limit's reset. */
function retryAtFrom(
headers: Readonly<Record<string, string | undefined>>,
now: number,
): number | undefined {
const fromRetryAfter = SourceControlRateLimit.retryAtFromHeader(headers["retry-after"], now);
if (fromRetryAfter !== undefined) return fromRetryAfter;
const reset = Number(headers["x-ratelimit-reset"]) * 1_000;
return Number.isFinite(reset) && reset > now ? reset : undefined;
}
const decodeGraphQlErrors = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
errors: Schema.NonEmptyArray(
Schema.Struct({
type: Schema.optional(Schema.String),
message: Schema.optional(Schema.String),
}),
),
}),
),
);
/** A REST failure body: `{ message, errors: [{ message } | { resource, field, code }] }`. */
const decodeRestErrors = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
message: Schema.optional(Schema.String),
errors: Schema.optional(
Schema.Array(
Schema.Union([
Schema.String,
Schema.Struct({
message: Schema.optional(Schema.String),
field: Schema.optional(Schema.String),
code: Schema.optional(Schema.String),
}),
]),
),
),
}),
),
);
function restErrorMessages(body: string): ReadonlyArray<string> | undefined {
return Option.match(decodeRestErrors(body), {
onNone: () => undefined,
onSome: (decoded) => {
const details = (decoded.errors ?? []).flatMap((error) =>
typeof error === "string"
? [error]
: error.message !== undefined
? [error.message]
: error.field !== undefined && error.code !== undefined
? [`${error.field} ${error.code}`]
: [],
);
const messages = [...(decoded.message === undefined ? [] : [decoded.message]), ...details];
return messages.length > 0 ? messages : undefined;
},
});
}
/** What one GitHub answer means, decided once from its status, headers and body. */
type Answer = Data.TaggedEnum<{
Ok: {};
RateLimited: {};
Unauthorized: {};
NotFound: {};
Failed: { readonly messages: ReadonlyArray<string> | undefined };
}>;
const Answer = Data.taggedEnum<Answer>();
/**
* GitHub reports a failed GraphQL document with HTTP 200 and an `errors` list, so a GraphQL body
* is read for its error types as well as its status. `gh api graphql` failed those too, and
* callers rely on that to fall back to narrower reads.
*/
function classify(input: {
readonly status: number;
readonly headers: Readonly<Record<string, string | undefined>>;
readonly body: string;
readonly graphql: boolean;
readonly acceptNotModified: boolean;
}): Answer {
const { status, headers, body } = input;
const errors = input.graphql
? Option.getOrUndefined(decodeGraphQlErrors(body))?.errors
: undefined;
const types = errors?.flatMap((error) => (error.type === undefined ? [] : [error.type])) ?? [];
const messages = errors?.flatMap((error) => (error.message === undefined ? [] : [error.message]));
if (
status === 429 ||
types.includes("RATE_LIMITED") ||
// An exhausted GraphQL quota can answer HTTP 200 with an untyped "API rate limit already
// exceeded" error; the headers say the same thing.
(input.graphql && errors !== undefined && headers["x-ratelimit-remaining"] === "0") ||
(input.graphql &&
messages !== undefined &&
messages.some((message) => /rate limit (already )?exceeded/i.test(message))) ||
(status === 403 &&
(headers["x-ratelimit-remaining"] === "0" ||
headers["retry-after"] !== undefined ||
/rate limit/i.test(body)))
) {
return Answer.RateLimited();
}
if (status === 401) return Answer.Unauthorized();
if (
status === 404 ||
(errors !== undefined && errors.every((error) => error.type === "NOT_FOUND"))
) {
return Answer.NotFound();
}
if (errors !== undefined) return Answer.Failed({ messages });
if ((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified)) {
return Answer.Ok();
}
return Answer.Failed({ messages: input.graphql ? undefined : restErrorMessages(body) });
}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const credentials = yield* GitHubCredentials.GitHubCredentials;
const quota = yield* GitHubQuota.GitHubQuota;
const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
const gate = yield* Semaphore.make(CONCURRENCY);
const credential: GitHubApi["Service"]["credential"] = Effect.fn("GitHubApi.credential")(
function* (host) {
const normalized = normalizeHost(host);
const pinned = yield* PinnedGitHubCredential;
if (pinned !== null) {
// A pinned page only ever talks to the host it verified.
if (pinned.host !== normalized) {
return yield* new GitHubApiAuthenticationError({
host: normalized,
operation: "credential",
});
}
return { token: pinned.token, fingerprint: pinned.credentialFingerprint };
}
const held = yield* credentials.get(normalized);
return { token: held.token, fingerprint: held.fingerprint };
},
);
/**
* Sends one request under the host's rate-limit pause and fails a refusal with the error that
* says why. `onSuccess` sees the answer only once it is known to be one.
*/
const send = Effect.fn("GitHubApi.send")(function* (input: {
readonly host: string;
readonly operation: string;
readonly request: HttpClientRequest.HttpClientRequest;
readonly maxResponseBytes: number;
readonly timeout?: Duration.Input | undefined;
readonly allowReserve: boolean;
readonly acceptNotModified: boolean;
/** Reads the body for GraphQL `errors`, which GitHub sends with HTTP 200. */
readonly graphql?: boolean;
}) {
const host = normalizeHost(input.host);
// Only the path: a query string can carry a SHA or a branch, and never needs to be in a trace.
yield* Effect.annotateCurrentSpan({
"github.host": host,
"github.operation": input.operation,
"github.kind": input.graphql === true ? "graphql" : "rest",
"http.request.method": input.request.method,
"url.path": new URL(input.request.url).pathname,
});
const { token, fingerprint } = yield* credential(host);
const scope = yield* SourceControlRateLimit.CredentialScope;
// REST spends `core` and GraphQL its own quota, each with its own reserve. Every REST path
// this reads today is `core`; a `search/` read would need its own resource here. A refusal
// still pauses the whole host, the key PullRequestService records its own backoff under.
const resource = input.graphql === true ? "graphql" : "core";
const key = { provider: "github" as const, host };
const run = Effect.gen(function* () {
const lease = yield* quota
.admit(host, resource, { allowReserve: input.allowReserve })
.pipe(
Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),
)
.pipe(
Effect.tapError((paused) =>
Effect.annotateCurrentSpan({
"github.paused": true,
"github.retry_at": paused.retryAt,
}),
),
);
// One deadline covers the headers and the body: a host that answers headers and then stalls
// must not hold a slot of the shared gate for undici's own five-minute body timeout.
const { response, collected } = yield* Effect.gen(function* () {
const response: HttpClientResponse.HttpClientResponse = yield* httpClient
.execute(
input.request.pipe(
HttpClientRequest.bearerToken(Redacted.value(token)),
HttpClientRequest.setHeaders({
"x-github-api-version": API_VERSION,
"user-agent": "t3code",
}),
),
)
.pipe(
// `GitHubApi.send` is the request's span. The client's own span would add `url.full`
// and `url.query`, which can carry SHAs and branch names, so it is off for GitHub.
Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
);
const collected = yield* collectUint8StreamText({
stream: response.stream,
maxBytes: input.maxResponseBytes,
}).pipe(
// 204, 304 and many refusals carry no body at all, which is an empty answer.
Effect.catchIf(
(error) => error.reason._tag === "EmptyBodyError",
() => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
),
);
return { response, collected };
}).pipe(
Effect.timeout(input.timeout ?? DEFAULT_TIMEOUT),
Effect.mapError(
(cause) => new GitHubApiRequestError({ host, operation: input.operation, cause }),
),
);
const headers = response.headers;
const status = response.status;
yield* quota.observe(host, headers);
yield* Effect.annotateCurrentSpan({
"http.response.status_code": status,
...rateLimitAttributes(headers),
});
const context = { host, operation: input.operation };
return yield* Answer.$match(
classify({
status,
headers,
body: collected.text,
graphql: input.graphql === true,
acceptNotModified: input.acceptNotModified,
}),
{
Ok: () =>
limits.recordSuccess({ ...key, lease }).pipe(
Effect.as({
status,
headers,
body: collected.text,
truncated: collected.truncated,
invalidUtf8: collected.invalidUtf8,
}),
),
RateLimited: () =>
Effect.gen(function* () {
const retryAt = retryAtFrom(headers, yield* Clock.currentTimeMillis);
yield* limits.recordRateLimit({ ...key, lease, retryAt });
yield* Effect.annotateCurrentSpan({
"github.rate_limited": true,
...(retryAt === undefined ? {} : { "github.retry_at": retryAt }),
});
return yield* new GitHubApiRateLimitError({
...context,
...(retryAt === undefined ? {} : { retryAt }),
});
}),
// The source may hold a newer token than the one that was refused.
Unauthorized: () =>
credentials
.invalidate(host)
.pipe(Effect.andThen(Effect.fail(new GitHubApiAuthenticationError(context)))),
NotFound: () => Effect.fail(new GitHubApiNotFoundError(context)),
Failed: ({ messages }) =>
Effect.fail(
new GitHubApiResponseError({
...context,
status,
...(messages === undefined ? {} : { githubErrors: messages }),
}),
),
},
);
});
// The rate-limit scope follows the credential, so a pause on one account never blocks another.
return yield* gate
.withPermit(run)
.pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope || fingerprint));
});
const rest: GitHubApi["Service"]["rest"] = (input) => {
const url = `${gitHubApiUrls(input.host).rest}/${input.path.replace(/^\/+/, "")}`;
const base = HttpClientRequest.make(input.method ?? "GET")(url).pipe(
HttpClientRequest.setHeader("accept", input.accept ?? "application/vnd.github+json"),
);
const withEtag =
input.ifNoneMatch === undefined
? base
: base.pipe(HttpClientRequest.setHeader("if-none-match", input.ifNoneMatch));
const request =
input.body === undefined
? withEtag
: withEtag.pipe(HttpClientRequest.bodyJsonUnsafe(input.body));
return AllowGitHubReserve.pipe(
Effect.flatMap((interactive) =>
send({
host: input.host,
operation: input.operation,
request,
maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
timeout: input.timeout,
allowReserve: input.allowReserve ?? interactive,
acceptNotModified: input.ifNoneMatch !== undefined,
}),
),
);
};
const graphql: GitHubApi["Service"]["graphql"] = Effect.fn("GitHubApi.graphql")(
function* (input) {
const host = normalizeHost(input.host);
const { fingerprint } = yield* credential(host);
const scope = (yield* SourceControlRateLimit.CredentialScope) || fingerprint;
const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);
// The document, never its variables: user text (bodies, search terms) travels as variables.
yield* Effect.annotateCurrentSpan({
"github.operation": input.operation,
"github.graphql.query_hash": queryHash(input.query),
"github.graphql.query":
input.query.length > TRACED_QUERY_MAX_CHARS
? `${input.query.slice(0, TRACED_QUERY_MAX_CHARS)}…`
: input.query,
});
return yield* Effect.gen(function* () {
const response = yield* send({
host,
operation: input.operation,
request: HttpClientRequest.post(gitHubApiUrls(host).graphql).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.bodyJsonUnsafe({
query: input.query,
variables: input.variables ?? {},
}),
),
maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
allowReserve,
acceptNotModified: false,
graphql: true,
});
// A body cut at the byte cap hides any `errors` past the cut and cannot be decoded.
if (response.truncated) {
return yield* new GitHubApiResponseError({
host,
operation: input.operation,
status: response.status,
});
}
return response.body;
}).pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, scope));
},
);
return GitHubApi.of({ graphql, rest, credential });
});
export const layer = Layer.effect(GitHubApi, make);
/**
* The transport with the credential, quota reserve and rate-limit pause it reads through. An
* application builds this once so every GitHub reader shares one view of each quota per host.
*/
export const layerWithDependencies = layer.pipe(
Layer.provideMerge(GitHubCredentials.layer),
Layer.provideMerge(GitHubQuota.layer),
Layer.provideMerge(SourceControlRateLimit.layer),
);
@@ -0,0 +1,182 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import { ChildProcessSpawner } from "effect/process";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
import * as GitHubCredentials from "./GitHubCredentials.ts";
const TOKEN_VARIABLES = [
"GH_TOKEN",
"GITHUB_TOKEN",
"GH_ENTERPRISE_TOKEN",
"GITHUB_ENTERPRISE_TOKEN",
] as const;
/** Settings keep `enabled` explicit; a host the test leaves it off is enabled. */
const hostSettings = (
hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }>,
) =>
Object.fromEntries(
Object.entries(hosts).map(([host, choice]) => [host, { enabled: true, ...choice }]),
);
function harness(
hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }> = {},
signedOut: ReadonlyArray<string> = [],
tokens: Record<string, string> = {},
) {
const calls: Array<ReadonlyArray<string>> = [];
const run: SourceControlHost.SourceControlHost["Service"]["process"]["run"] = (input) =>
Effect.sync(() => {
calls.push(input.args);
const user = input.args[input.args.indexOf("--user") + 1];
if (input.args.includes("--user") && user !== undefined && signedOut.includes(user)) {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: input.args.includes("--user") ? `token-for-${user}\n` : "active-token\n",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
});
const layer = GitHubCredentials.layer.pipe(
Layer.provideMerge(
TestSourceControlHost.layer({
settings: applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
github: { hosts: hostSettings(hosts), tokens },
}),
process: { run },
}),
),
Layer.provide(NodeCrypto.layer),
);
return { layer, calls };
}
describe("GitHubCredentials", () => {
beforeEach(() => {
for (const name of TOKEN_VARIABLES) vi.stubEnv(name, "");
});
afterEach(() => {
vi.unstubAllEnvs();
});
it.effect("asks gh for the active login when Settings pin nothing", () => {
const { layer, calls } = harness();
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const credential = yield* credentials.get("GitHub.com");
expect(Redacted.value(credential.token)).toBe("active-token");
expect(calls).toEqual([["auth", "token", "--hostname", "github.com"]]);
}).pipe(Effect.provide(layer));
});
it.effect("passes --user for an account pinned in Settings", () => {
const { layer, calls } = harness({ "github.com": { account: "work" } });
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const credential = yield* credentials.get("github.com");
expect(Redacted.value(credential.token)).toBe("token-for-work");
expect(calls).toEqual([["auth", "token", "--hostname", "github.com", "--user", "work"]]);
}).pipe(Effect.provide(layer));
});
it.effect("fails a host turned off in Settings without asking gh", () => {
const { layer, calls } = harness({ "github.com": { enabled: false } });
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const error = yield* Effect.flip(credentials.get("github.com"));
expect(error._tag).toBe("GitHubHostDisabledError");
expect(error.message).toBe(
"GitHub host github.com is turned off in Settings → Source Control.",
);
expect(calls).toEqual([]);
}).pipe(Effect.provide(layer));
});
it.effect("lets an environment token win over a pinned account, as gh does", () => {
vi.stubEnv("GH_TOKEN", "from-env");
const { layer, calls } = harness({ "github.com": { account: "work" } });
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const credential = yield* credentials.get("github.com");
expect(Redacted.value(credential.token)).toBe("from-env");
expect(credential.source).toBe("env");
expect(calls).toEqual([]);
}).pipe(Effect.provide(layer));
});
it.effect("picks up a changed account on the next request without a restart", () => {
const { layer, calls } = harness();
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
yield* settings.update({
github: { hosts: { "github.com": { account: "work", enabled: true } } },
});
expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("token-for-work");
yield* settings.update({ github: { hosts: { "github.com": { enabled: false } } } });
expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(
"GitHubHostDisabledError",
);
yield* settings.update({ github: { hosts: {} } });
expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
// The unpinned token stayed cached; only the newly pinned account cost a gh call.
expect(calls).toHaveLength(2);
}).pipe(Effect.provide(layer));
});
it.effect("falls back to the active login when the pinned one is no longer signed in", () => {
const { layer, calls } = harness({ "github.com": { account: "gone" } }, ["gone"]);
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
expect(calls).toEqual([
["auth", "token", "--hostname", "github.com", "--user", "gone"],
["auth", "token", "--hostname", "github.com"],
]);
}).pipe(Effect.provide(layer));
});
it.effect("uses a token saved in Settings before GH_TOKEN and gh", () => {
vi.stubEnv("GH_TOKEN", "env-token");
const { layer, calls } = harness({}, [], { "github.com": "saved-token" });
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
const credential = yield* credentials.get("github.com");
expect(Redacted.value(credential.token)).toBe("saved-token");
expect(credential.source).toBe("settings");
expect(calls).toEqual([]);
}).pipe(Effect.provide(layer));
});
it.effect("keeps a host turned off even with a token saved in Settings", () => {
const { layer } = harness({ "github.com": { enabled: false } }, [], {
"github.com": "saved-token",
});
return Effect.gen(function* () {
const credentials = yield* GitHubCredentials.GitHubCredentials;
expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(
"GitHubHostDisabledError",
);
}).pipe(Effect.provide(layer));
});
});
@@ -0,0 +1,261 @@
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Exit from "effect/Exit";
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 Schema from "effect/Schema";
import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
/** How long a token is reused before `gh` is asked again, so a `gh auth switch` applies soon. */
const TOKEN_TTL = Duration.minutes(5);
/** No credential is retried sooner, so a fresh `gh auth login` takes effect on the next read. */
const MISSING_TTL = Duration.seconds(10);
export const GitHubCredentialSource = Schema.Literals(["settings", "env", "gh"]);
export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;
export interface GitHubCredential {
readonly host: string;
readonly token: Redacted.Redacted<string>;
readonly source: GitHubCredentialSource;
/** A digest of host and token: safe for cache keys and rate-limit scopes, never the token. */
readonly fingerprint: string;
}
/** Nothing in the environment, and no `gh` on PATH to ask. */
export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingError>()(
"GitHubCliMissingError",
{ host: Schema.String },
) {
override get message(): string {
return `No GitHub credential for ${this.host}: set GH_TOKEN, or install the GitHub CLI and run \`gh auth login\`.`;
}
}
/** `gh` is installed but holds no login for the host, or not the account chosen in Settings. */
export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()(
"GitHubNotSignedInError",
{ host: Schema.String, account: Schema.optional(Schema.String) },
) {
override get message(): string {
return this.account === undefined
? `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`
: `No GitHub credential for ${this.account} on ${this.host}: run \`gh auth login --hostname ${this.host}\` for that account or pick another in Settings → Source Control.`;
}
}
/** The user turned the host off in Settings. */
export class GitHubHostDisabledError extends Schema.TaggedError<GitHubHostDisabledError>()(
"GitHubHostDisabledError",
{ host: Schema.String },
) {
override get message(): string {
return `GitHub host ${this.host} is turned off in Settings → Source Control.`;
}
}
/** `gh auth token` timed out or failed for a reason other than having no login. */
export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedError>()(
"GitHubCliFailedError",
{ host: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `The GitHub CLI could not hand over a credential for ${this.host}. Check \`gh auth status\` on the server.`;
}
}
/** There is no token for the host. */
export type GitHubCredentialUnavailableError =
| GitHubCliMissingError
| GitHubNotSignedInError
| GitHubHostDisabledError
| GitHubCliFailedError;
/**
* Where GitHub tokens come from. Callers ask per host and never see how the token was found,
* so another source (an in-app OAuth login) slots in here without touching any of them.
*/
export class GitHubCredentials extends Context.Service<
GitHubCredentials,
{
readonly get: (
host: string,
) => Effect.Effect<GitHubCredential, GitHubCredentialUnavailableError>;
/** Drops the held token after GitHub refused it, so the next read asks its source again. */
readonly invalidate: (host: string) => Effect.Effect<void>;
}
>()("@t3tools/source-control-github/server/GitHubCredentials") {}
function normalizeHost(host: string): string {
return host.trim().toLowerCase();
}
/** Hosts gh treats as GitHub.com-like for `GH_TOKEN`: github.com and GHE.com data residency. */
function isGitHubDotCom(host: string): boolean {
return host === "github.com" || host.endsWith(".ghe.com");
}
/**
* The environment token for a host, in gh's precedence order. gh hands `GH_ENTERPRISE_TOKEN` to
* any non-github.com host; here it only goes to the host `GH_HOST` names, because a remote URL
* picks the host and a hostile one must not receive an enterprise token.
*/
export function environmentToken(
host: string,
env: Readonly<Record<string, string | undefined>>,
): string | null {
const names = isGitHubDotCom(host)
? ["GH_TOKEN", "GITHUB_TOKEN"]
: env.GH_HOST?.trim().toLowerCase() === host
? ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
: [];
for (const name of names) {
const value = env[name]?.trim();
if (value) return value;
}
return null;
}
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const sourceControlHost = yield* SourceControlHost.SourceControlHost;
const process = sourceControlHost.process;
const crypto = yield* Crypto.Crypto;
const environment = yield* HostProcessEnvironment;
const workingDirectory = yield* HostProcessWorkingDirectory;
/** `host:sha256(token)`, safe for cache keys and rate-limit scopes. */
const fingerprintOf = (host: string, token: string) =>
crypto.digest("SHA-256", new TextEncoder().encode(token)).pipe(
Effect.map((digest) => `${host}:${Hex.encode(digest)}`),
// Hashing a string in memory has no platform failure worth a typed error.
Effect.orDie,
);
const fromGh = (host: string, account: string | undefined) =>
process
.run({
operation: "GitHubCredentials.get",
command: "gh",
args: [
"auth",
"token",
"--hostname",
host,
...(account === undefined ? [] : ["--user", account]),
],
cwd: workingDirectory,
// Never let gh print the token into a debug log.
env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
timeoutMs: 10_000,
})
.pipe(
Effect.mapError((error) =>
error._tag === "VcsProcessSpawnError" &&
error.cause instanceof PlatformError.PlatformError &&
error.cause.reason._tag === "NotFound"
? new GitHubCliMissingError({ host })
: // gh exits non-zero with "no oauth token" when it has no login for the host.
error._tag === "VcsProcessExitError"
? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) })
: new GitHubCliFailedError({ host, cause: error }),
),
Effect.map((output) => output.stdout.trim()),
Effect.filterOrFail(
(token) => token !== "",
() => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),
),
);
/** The Settings choice for a host; unreadable settings fall back to gh's own choice. */
const hostChoice = (host: string) =>
sourceControlHost.settings.get.pipe(
Effect.map((settings) => settings.github.hosts[host]),
Effect.orElseSucceed(() => undefined),
);
/** A token saved in Settings for the host, read fresh so a saved or removed one applies at once. */
const savedToken = (host: string) =>
sourceControlHost.settings.get.pipe(
Effect.map((settings) => settings.github.tokens[host]?.trim() || null),
Effect.orElseSucceed(() => null),
);
/** Cache key: the host plus its pinned account, so a changed pin misses the cache. */
const cacheKey = (host: string, account: string | undefined) =>
account === undefined ? host : `${host}\u0000${account}`;
const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {
const [host = key, choice] = key.split("\u0000");
// An environment token wins over a pinned account, exactly as it does in gh.
const fromEnv = environmentToken(host, environment);
// A pinned login gh no longer holds (logged out, expired) falls back to the active one,
// which is what discovery reports as the account in use.
const token =
fromEnv ??
(yield* fromGh(host, choice).pipe(
Effect.catchTags({
GitHubNotSignedInError: (error) =>
choice === undefined ? Effect.fail(error) : fromGh(host, undefined),
}),
));
return {
host,
token: Redacted.make(token),
source: fromEnv !== null ? "env" : "gh",
fingerprint: yield* fingerprintOf(host, token),
} satisfies GitHubCredential;
});
const cache = yield* Cache.makeWith(lookup, {
capacity: 32,
// A transient gh failure (a timeout, a locked keyring) is asked again on the next read.
timeToLive: (exit) =>
Exit.isSuccess(exit)
? TOKEN_TTL
: Exit.findErrorOption(exit).pipe(
Option.exists((error) => error._tag === "GitHubCliFailedError"),
)
? Duration.zero
: MISSING_TTL,
});
return GitHubCredentials.of({
get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {
const host = normalizeHost(rawHost);
const choice = yield* hostChoice(host);
if (choice?.enabled === false) {
return yield* new GitHubHostDisabledError({ host });
}
// A token saved in Settings is the most deliberate choice, so it comes before the
// environment and gh. It is read from the secret store each time, so it needs no cache.
const saved = yield* savedToken(host);
if (saved !== null) {
return {
host,
token: Redacted.make(saved),
source: "settings",
fingerprint: yield* fingerprintOf(host, saved),
} satisfies GitHubCredential;
}
return yield* Cache.get(cache, cacheKey(host, choice?.account));
}),
invalidate: (rawHost) => {
const host = normalizeHost(rawHost);
return hostChoice(host).pipe(
Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),
);
},
});
});
export const layer = Layer.effect(GitHubCredentials, make);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,672 @@
import * as Effect from "effect/Effect";
import type {
PullRequestActor,
PullRequestCapabilities,
PullRequestCheck,
PullRequestReaction,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
import * as GitHubApi from "./GitHubApi.ts";
import * as GitHubPullRequestApi from "./GitHubPullRequestApi.ts";
import {
PullRequestProviderError,
type PullRequestProviderFailure,
type ProviderChangeRequestActivity,
type ProviderChangeRequestDetail,
type PullRequestProviderApi,
type ProviderRepositoryRef,
} from "@t3tools/source-control-core/server/PullRequestProvider";
import type { GitHubViewerAccess, GitHubWorkflowRunApproval } from "./gitHubPullRequestJson.ts";
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
actions: [
"merge",
"ready",
"draft",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
"revert",
"approve-workflows",
],
mergeMethods: ["merge", "squash", "rebase"],
updateMethods: ["merge", "rebase"],
search: true,
reactions: true,
viewedFiles: "host",
review: {
inlineComment: true,
reply: true,
resolve: true,
verdicts: ["comment", "approve", "request-changes"],
},
reviewers: { request: true, listCandidates: true },
edit: { changeRequest: true, comment: true },
stacks: true,
stackActions: true,
labels: true,
};
/**
* What the signed-in account may do here, from the three things GitHub says about it.
*
* Merging needs a role that can push, which is the one thing a stranger on an open-source
* repository never has. The other four actions go by `viewerCanUpdate`, because the author of a
* pull request may close it, reopen it and move it in and out of draft with no more than read
* access on the repository it was opened against.
*
* Commenting and reviewing are not gated at all: read access is enough to say something and
* enough to approve or ask for changes, which is what open-source review consists of. Resolving a
* conversation is the exception — GitHub allows it to whoever can write, and to the author of the
* pull request the conversation is on.
*
* Asking somebody else for a review needs write access, which is the one thing here an author
* cannot do on their own pull request: GitHub shows an outside contributor the reviewer control
* and refuses the request behind it.
*/
export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequestViewerPermissions {
return {
...(access.canWrite ? { stackRebase: true } : {}),
actions: [
// Arming a merge and taking the arming back are the merge, deferred: whoever may not
// merge here may not leave an instruction to merge later either.
...(access.canWrite
? ([
"merge",
"enable-auto-merge",
"disable-auto-merge",
"revert",
"approve-workflows",
] as const)
: []),
...(access.canUpdate ? (["ready", "draft", "close", "reopen"] as const) : []),
// Whether this viewer may update the branch is GitHub's own answer, read with the
// comparison; without it the action is offered to nobody rather than to everybody.
...(access.canUpdateBranch === true ? (["update-branch"] as const) : []),
],
comment: true,
resolve: access.canWrite || access.didAuthor,
// Anyone may review a pull request they can see, except their own: GitHub refuses an author's
// approval and their request for changes ("Can not approve your own pull request"), and
// leaves them commenting, which is what an author has to say about their own change anyway.
verdicts: access.didAuthor ? (["comment"] as const) : CAPABILITIES.review.verdicts,
requestReviewers: access.canWrite,
...(access.canUpdateBranch === true ? { updateMethods: CAPABILITIES.updateMethods } : {}),
// Triage is the one role that labels without writing, which is what triage is for.
labels: access.canTriage,
};
}
/** The tags that mean GitHub is out of reach for this account, rather than one request failing. */
export function gitHubProviderFailure(
error: GitHubPullRequestApi.GitHubPullRequestApiError,
): PullRequestProviderFailure {
switch (error._tag) {
case "GitHubCliMissingError":
return { reason: "missing-tool" };
case "GitHubNotSignedInError":
case "GitHubHostDisabledError":
case "GitHubApiAuthenticationError":
return { reason: "unauthenticated" };
case "GitHubApiRateLimitError":
return {
reason: "rate-limited",
...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
};
case "SourceControlRateLimitPausedError":
return { reason: "rate-limited", retryAt: error.retryAt };
case "GitHubApiNotFoundError":
return { reason: "not-found" };
default:
return { reason: "failed" };
}
}
/**
* `gh pr view --json` reports no avatar for anyone, so the ones the GraphQL read collected are
* applied here by login. An actor already carrying one keeps it.
*
* A login GitHub did not answer for falls back to the picture every GitHub install serves at
* `/<login>.png`. The lookup is one more request per repository and can be refused — a rate
* limit, a slow host — and a face that comes and goes between two loads of the same page reads
* as a bug in the page rather than as a request that failed quietly.
*/
function withAvatar(
actor: PullRequestActor | null,
avatarsByLogin: ReadonlyMap<string, string>,
host: string,
botLogins?: ReadonlySet<string>,
): PullRequestActor | null {
if (actor === null) return actor;
if (botLogins?.has(actor.login)) actor = { ...actor, isBot: true };
if (actor.avatarUrl !== null) return actor;
const avatarUrl = avatarsByLogin.get(actor.login) ?? loginAvatarUrl(actor.login, host);
return avatarUrl === null ? actor : { ...actor, avatarUrl };
}
function withWorkflowApprovals(
checks: ReadonlyArray<PullRequestCheck>,
runs: ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: boolean,
): ReadonlyArray<PullRequestCheck> {
const representedRunIds = new Set<number>();
for (const check of checks) {
if (check.status !== "action-required" || check.url === null) continue;
const id = check.url.match(/\/actions\/runs\/(\d+)(?:\/|$)/)?.[1];
if (id !== undefined) representedRunIds.add(Number(id));
}
const approvalChecks = runs
.filter((run) => !representedRunIds.has(run.id))
.map((run): PullRequestCheck => ({
name: run.name,
status: "action-required",
description: "A maintainer must approve this workflow before it can run.",
url: run.url,
}));
return [
...checks,
...approvalChecks,
...(unavailable
? [
{
name: "Workflow approval status",
status: "action-required" as const,
description: "GitHub could not determine whether workflows are awaiting approval.",
url: null,
},
]
: []),
];
}
/**
* Null for anything that is not a plain user login: an app posts as `dependabot[bot]`, which
* names no page, and a guessed URL that 404s is worse than the initials it would replace.
*/
export function loginAvatarUrl(login: string, host: string): string | null {
return /^[a-z0-9][a-z0-9-]{0,38}$/iu.test(login) ? `https://${host}/${login}.png?size=80` : null;
}
/** True where markdown would render nothing: whitespace, or only HTML comments. */
const rendersEmpty = (body: string): boolean =>
body.replace(/<!--[\s\S]*?-->/g, "").trim().length === 0;
export const make = Effect.gen(function* () {
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
const fail = (operation: string) => (error: GitHubPullRequestApi.GitHubPullRequestApiError) =>
new PullRequestProviderError({
provider: "github",
operation,
...gitHubProviderFailure(error),
detail: error.message,
cause: error,
});
const readChecks = (input: ProviderRepositoryRef & { readonly number: number }) =>
cli.getPullRequestDetail(input).pipe(
Effect.flatMap((pullRequest) =>
(pullRequest.state !== "open" || pullRequest.isCrossRepository !== true
? Effect.succeed({
runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: false,
})
: pullRequest.headSha == null || pullRequest.headRepositoryOwner == null
? Effect.succeed({
runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: true,
})
: cli
.listWorkflowRunsRequiringApproval({
...input,
headSha: pullRequest.headSha,
headBranch: pullRequest.headBranch,
headRepositoryOwner: pullRequest.headRepositoryOwner,
isCrossRepository: true,
})
.pipe(
Effect.matchEffect({
onFailure: (error) =>
error._tag === "GitHubApiRateLimitError" ||
error._tag === "SourceControlRateLimitPausedError"
? Effect.fail(error)
: Effect.succeed({
runs: [] as ReadonlyArray<GitHubWorkflowRunApproval>,
unavailable: true,
}),
onSuccess: (runs) => Effect.succeed({ runs, unavailable: false }),
}),
)
).pipe(
Effect.map((workflowApprovals) => ({
...pullRequest,
author: withAvatar(pullRequest.author, new Map(), input.host),
checks: withWorkflowApprovals(
pullRequest.checks,
workflowApprovals.runs,
workflowApprovals.unavailable,
),
...(workflowApprovals.unavailable
? {}
: { workflowApprovalsRequired: workflowApprovals.runs.length }),
})),
),
),
);
const provider: PullRequestProviderApi = {
kind: "github",
capabilities: CAPABILITIES,
getRoutingIdentity: (input) =>
cli.getRoutingIdentity(input).pipe(Effect.mapError(fail("routeIdentity"))),
withVerifiedCredential: (input, use) =>
cli
.withVerifiedCredential(input, (identity) => use(identity).pipe(Effect.result))
.pipe(Effect.mapError(fail("routeIdentity")), Effect.flatMap(Effect.fromResult)),
getViewer: (input) =>
cli
.getViewerLogin({ cwd: input.cwd, host: input.host ?? "github.com" })
.pipe(Effect.mapError(fail("getViewer"))),
listChangeRequests: (input) =>
cli
.listPullRequests({
cwd: input.cwd,
repository: input.repository,
host: input.host,
state: input.state,
involvement: input.involvement,
viewer: input.viewer,
limit: input.limit,
query: input.query,
cursor: input.cursor,
filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequests")),
Effect.flatMap((page) =>
cli
.listActorAvatars({
cwd: input.cwd,
repository: input.repository,
host: input.host,
ids: [...new Set(page.items.flatMap((item) => item.authorId ?? []))],
})
// A listing without faces is still a listing, so a failed lookup falls back to
// the initials rather than taking the rows down with it.
.pipe(
Effect.orElseSucceed(() => new Map<string, string>()),
Effect.map((avatarsByLogin) => ({
...page,
items: page.items.map((item) => ({
...item,
author: withAvatar(item.author, avatarsByLogin, input.host),
})),
})),
),
),
),
/**
* The same listing for a whole host in one search. The avatar lookup the per-repository read
* needs is not here: a search reports an author's picture itself, so a face costs no request
* of its own — `withAvatar` still stands behind it for the login GitHub answered nothing for.
*/
listChangeRequestsAcross: (input) =>
cli
.searchPullRequests({
cwd: input.cwd,
host: input.host,
repositories: input.repositories,
state: input.state,
involvement: input.involvement,
viewer: input.viewer,
limit: input.limit,
query: input.query,
cursor: input.cursor,
filters: input.filters,
})
.pipe(
Effect.mapError(fail("listChangeRequestsAcross")),
Effect.map((batch) => ({
truncated: batch.truncated,
items: batch.items.map((item) => ({
...item,
author: withAvatar(item.author, new Map<string, string>(), input.host),
})),
})),
),
listChangeRequestStats: (input) =>
cli
.listPullRequestStats({
cwd: input.cwd,
host: input.host,
changeRequests: input.changeRequests,
})
.pipe(Effect.mapError(fail("listChangeRequestStats"))),
getChangeRequestSummary: (input) =>
cli.getPullRequestSummary(input).pipe(
// `gh pr view` names the author without an avatar; the login-shaped URL every user
// has stands in, without the second request the listing spends on it.
Effect.map((summary) => ({
...summary,
...(summary.author === undefined
? {}
: { author: withAvatar(summary.author, new Map(), input.host) }),
})),
Effect.mapError(fail("getChangeRequestSummary")),
),
getChangeRequestStack: (input) =>
cli.getPullRequestStack(input).pipe(Effect.mapError(fail("getChangeRequestStack"))),
getChangeRequestWatchFingerprint: (input) =>
cli
.getPullRequestWatchFingerprint(input)
.pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))),
getChangeRequestPreview: (input) =>
cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
getChangeRequestChecks: (input) =>
cli.revalidateChecks(input, readChecks(input)).pipe(
Effect.map(({ state, checks }) => ({ state, checks })),
Effect.mapError(fail("getChangeRequestChecks")),
),
getChangeRequest: (input) =>
readChecks(input).pipe(
Effect.map((pullRequest): ProviderChangeRequestDetail => ({
...pullRequest,
author: withAvatar(pullRequest.author, new Map<string, string>(), input.host),
reviewers: pullRequest.reviewRequestLogins.map((login) => ({
login,
name: null,
avatarUrl: null,
})),
mergeCapabilities: pullRequest.viewerAccess.mergeCapabilities,
viewerPermissions: gitHubViewerPermissions({
...pullRequest.viewerAccess,
canUpdateBranch: pullRequest.comparison?.viewerCanUpdate === true,
}),
baseComparison:
pullRequest.comparison === null || pullRequest.comparison.behindBy === null
? "unknown"
: pullRequest.comparison.behindBy > 0
? "behind"
: "up-to-date",
...(pullRequest.comparison?.behindBy == null
? {}
: { behindBy: pullRequest.comparison.behindBy }),
})),
Effect.mapError(fail("getChangeRequest")),
),
getChangeRequestActivity: (input) =>
Effect.all(
[
cli.getPullRequestActivity(input),
// Line comments live on review threads, which `gh pr view --json` cannot reach. A
// GraphQL hiccup degrades to a truncated conversation rather than blanking activity.
cli.listReviewThreadComments(input).pipe(
Effect.orElseSucceed(() => ({
comments: [],
dismissalsByReviewId: new Map<string, string>(),
reactions: [],
reactionsById: new Map<string, ReadonlyArray<PullRequestReaction>>(),
editedAtById: new Map<string, string>(),
reviewThreads: [],
commentCount: 0,
truncated: true,
reviewThreadsTruncated: true,
reviewers: [],
avatarsByLogin: new Map<string, string>(),
botLogins: new Set<string>(),
commitStats: new Map<
string,
{ readonly additions: number; readonly deletions: number }
>(),
commits: [],
viewer: { canUpdate: true, didAuthor: false },
})),
),
],
{ concurrency: 2 },
).pipe(
Effect.mapError(fail("getChangeRequestActivity")),
Effect.map(([pullRequest, reviewThreads]): ProviderChangeRequestActivity => ({
author: withAvatar(
pullRequest.author,
reviewThreads.avatarsByLogin,
input.host,
reviewThreads.botLogins,
),
reviewers: reviewThreads.reviewers,
reactions: reviewThreads.reactions,
commits: (reviewThreads.commits.length > 0
? reviewThreads.commits
: pullRequest.commits
).map((commit) => ({
...commit,
...reviewThreads.commitStats.get(commit.oid),
authors: commit.authors?.map(
(author) =>
withAvatar(
author,
reviewThreads.avatarsByLogin,
input.host,
reviewThreads.botLogins,
) ?? author,
),
})),
comments: [...pullRequest.comments, ...reviewThreads.comments]
.map((comment) => ({
...comment,
// GitHub keeps the dismissal reason on the timeline event, not on the review,
// so a dismissed review with nothing visible of its own reads its words from
// there. "Visible" and not "empty": bot reviews often carry only an HTML
// marker comment, which markdown renders as nothing.
body:
comment.kind === "review" &&
comment.reviewState?.toUpperCase() === "DISMISSED" &&
rendersEmpty(comment.body)
? (reviewThreads.dismissalsByReviewId.get(comment.id) ?? comment.body)
: comment.body,
author: withAvatar(
comment.author,
reviewThreads.avatarsByLogin,
input.host,
reviewThreads.botLogins,
),
// A comment out of `gh pr view --json` carries none of its own: that read
// reports no reaction at all, so they arrive from the GraphQL page by node id.
reactions: comment.reactions ?? reviewThreads.reactionsById.get(comment.id) ?? [],
editedAt: reviewThreads.editedAtById.get(comment.id) ?? comment.editedAt ?? null,
}))
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)),
// `gh pr view --json comments,reviews` follows GitHub's cursors itself, so those two
// are always whole and only the thread walk can stop short of the host.
commentCount: pullRequest.comments.length + reviewThreads.commentCount,
commentsTruncated: reviewThreads.truncated,
reviewThreadsTruncated: reviewThreads.reviewThreadsTruncated,
reviewThreads: reviewThreads.reviewThreads.map((thread) => ({
...thread,
comments: thread.comments.map((comment) => ({
...comment,
author: withAvatar(
comment.author,
reviewThreads.avatarsByLogin,
input.host,
reviewThreads.botLogins,
),
})),
})),
})),
),
getReviewThreadComments: (input) =>
cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),
getViewerPermissions: (input) => {
const lightAccess = cli
.getViewerAccess({ ...input, allowReserve: true })
.pipe(Effect.map((access) => gitHubViewerPermissions(access)));
if (input.includeUpdateBranch === false) {
return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));
}
// The core detail already carries the viewer's access, the merge settings, and the base
// comparison, so one read usually answers what used to take three. When that heavier read
// fails, the light access read still answers, withholding only update-branch.
return cli.getPullRequestDetail(input).pipe(
Effect.provideService(GitHubApi.AllowGitHubReserve, true),
Effect.map((pullRequest) =>
gitHubViewerPermissions({
...pullRequest.viewerAccess,
canUpdateBranch:
pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,
}),
),
Effect.catchIf(
(error) =>
error._tag !== "GitHubApiRateLimitError" &&
error._tag !== "SourceControlRateLimitPausedError",
() => lightAccess,
),
Effect.mapError(fail("getViewerPermissions")),
);
},
getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
getDiffFileContents: (input) =>
cli.getPullRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
getFilesViewed: (input) =>
cli.getPullRequestFilesViewed(input).pipe(Effect.mapError(fail("getFilesViewed"))),
setFilesViewed: (input) =>
cli.setPullRequestFilesViewed(input).pipe(Effect.mapError(fail("setFilesViewed"))),
listReviewerCandidates: (input) =>
cli.listReviewerCandidates(input).pipe(Effect.mapError(fail("listReviewerCandidates"))),
setReviewerRequest: (input) =>
cli
.setReviewerRequest({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
reviewers: input.reviewers,
requested: input.requested,
})
.pipe(Effect.mapError(fail("setReviewerRequest"))),
listLabelCandidates: (input) =>
cli.listLabelCandidates(input).pipe(Effect.mapError(fail("listLabelCandidates"))),
setLabels: (input) =>
cli
.setLabels({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
labels: input.labels,
applied: input.applied,
})
.pipe(Effect.mapError(fail("setLabels"))),
runAction: (input) =>
cli
.runPullRequestAction({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
action: input.action,
...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
...(input.stackNumber === undefined ? {} : { stackNumber: input.stackNumber }),
...(input.expectedStackHeads === undefined
? {}
: { expectedStackHeads: input.expectedStackHeads }),
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
...(input.updateMethod === undefined ? {} : { updateMethod: input.updateMethod }),
})
.pipe(Effect.mapError(fail("runAction"))),
updateChangeRequest: (input) =>
cli
.updatePullRequest({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { body: input.body }),
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
comment: (input) => cli.commentOnPullRequest(input).pipe(Effect.mapError(fail("comment"))),
updateComment: (input) =>
cli
.updateComment({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
commentId: input.commentId,
kind: input.kind,
body: input.body,
})
.pipe(Effect.mapError(fail("updateComment"))),
submitReview: (input) => cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
replyToThread: (input) =>
cli
.replyToReviewThread({
cwd: input.cwd,
repository: input.repository,
host: input.host,
threadId: input.threadId,
body: input.body,
})
.pipe(Effect.mapError(fail("replyToThread"))),
setReaction: (input) =>
cli
.setReaction({
cwd: input.cwd,
repository: input.repository,
host: input.host,
number: input.number,
...(input.subjectId === undefined ? {} : { subjectId: input.subjectId }),
content: input.content,
reacted: input.reacted,
})
.pipe(Effect.mapError(fail("setReaction"))),
setThreadResolution: (input) =>
cli
.setReviewThreadResolution({
cwd: input.cwd,
repository: input.repository,
host: input.host,
threadId: input.threadId,
resolved: input.resolved,
})
.pipe(Effect.mapError(fail("setThreadResolution"))),
};
return provider;
});
@@ -0,0 +1,86 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as TestClock from "effect/testing/TestClock";
import * as GitHubQuota from "./GitHubQuota.ts";
import { CredentialScope } from "@t3tools/source-control-core/server/SourceControlRateLimit";
const RESET = Date.parse("2099-08-13T14:00:00Z");
const headers = (remaining: number, resource = "graphql", reset = RESET) => ({
"x-ratelimit-resource": resource,
"x-ratelimit-limit": "5000",
"x-ratelimit-remaining": String(remaining),
"x-ratelimit-reset": String(reset / 1000),
});
describe("GitHubQuota", () => {
it.effect("refuses a background request below the reserve, per quota and account", () =>
Effect.gen(function* () {
const quota = yield* GitHubQuota.GitHubQuota;
yield* quota.observe("github.com", headers(499));
const refused = yield* Effect.flip(quota.admit("github.com", "graphql"));
assert.strictEqual(refused.retryAt, RESET);
// Another quota, another host and another account each have their own balance.
yield* quota.admit("github.com", "core");
yield* quota.admit("ghe.example", "graphql");
yield* quota.admit("github.com", "graphql").pipe(Effect.provideService(CredentialScope, "b"));
yield* quota.admit("github.com", "graphql", { allowReserve: true });
}).pipe(Effect.provide(GitHubQuota.layer)),
);
it.effect("takes the latest balance in a window, and ignores an older window", () =>
Effect.gen(function* () {
const quota = yield* GitHubQuota.GitHubQuota;
yield* quota.observe("github.com", headers(400));
yield* Effect.flip(quota.admit("github.com", "graphql"));
// GitHub can report more left later in the same window, from another region.
yield* quota.observe("github.com", headers(900));
yield* quota.admit("github.com", "graphql");
yield* quota.observe("github.com", headers(400));
yield* Effect.flip(quota.admit("github.com", "graphql"));
// An answer from an older window says nothing about this one.
yield* quota.observe("github.com", headers(4000, "graphql", RESET - 3_600_000));
yield* Effect.flip(quota.admit("github.com", "graphql"));
// A later window replaces it.
yield* quota.observe("github.com", headers(4000, "graphql", RESET + 3_600_000));
yield* quota.admit("github.com", "graphql");
}).pipe(Effect.provide(GitHubQuota.layer)),
);
it.effect("lets interactive requests spend the reserve but not an empty quota", () =>
Effect.gen(function* () {
const quota = yield* GitHubQuota.GitHubQuota;
yield* quota.observe("github.com", headers(1));
yield* quota.admit("github.com", "graphql", { allowReserve: true });
yield* quota.observe("github.com", headers(0));
const refused = yield* Effect.flip(
quota.admit("github.com", "graphql", { allowReserve: true }),
);
assert.strictEqual(refused.retryAt, RESET);
}).pipe(Effect.provide(GitHubQuota.layer)),
);
it.effect("spends nothing locally, so a free 304 cannot run the balance down", () =>
Effect.gen(function* () {
const quota = yield* GitHubQuota.GitHubQuota;
yield* quota.observe("github.com", headers(501, "core"));
// Conditional reads answer 304 with the balance unchanged, however many are sent.
for (let index = 0; index < 5; index++) {
yield* quota.admit("github.com", "core");
yield* quota.observe("github.com", headers(501, "core"));
}
yield* quota.admit("github.com", "core");
}).pipe(Effect.provide(GitHubQuota.layer)),
);
it.effect("forgets a balance once its window resets, and ignores answers naming no quota", () =>
Effect.gen(function* () {
const quota = yield* GitHubQuota.GitHubQuota;
yield* quota.observe("github.com", headers(0));
yield* TestClock.setTime(RESET);
yield* quota.admit("github.com", "graphql");
yield* quota.observe("other.example", { "x-ratelimit-remaining": "0" });
yield* quota.admit("other.example", "graphql");
}).pipe(Effect.provide(GitHubQuota.layer)),
);
});
@@ -0,0 +1,122 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
/** The share of each quota a background read leaves for a user's next click. */
const RESERVE_RATIO = 0.1;
/**
* GitHub's quotas: `core` for REST, `graphql` for GraphQL, and a few smaller ones (`search`, …).
* Each is spent and reset on its own, so each is tracked on its own.
*/
type GitHubQuotaResource = string;
interface QuotaSnapshot {
readonly limit: number;
readonly remaining: number;
readonly resetAtMs: number;
}
/**
* What GitHub says is left of one quota, from the `x-ratelimit-*` headers every API answer
* carries. Null when the answer named no quota, which an Enterprise host with limits off does.
*/
function quotaFromHeaders(
headers: Readonly<Record<string, string | undefined>>,
): (QuotaSnapshot & { readonly resource: GitHubQuotaResource }) | null {
const resource = headers["x-ratelimit-resource"]?.trim();
const limit = Number(headers["x-ratelimit-limit"]);
const remaining = Number(headers["x-ratelimit-remaining"]);
const reset = Number(headers["x-ratelimit-reset"]);
if (
!resource ||
!Number.isFinite(limit) ||
limit <= 0 ||
!Number.isFinite(remaining) ||
remaining < 0 ||
!Number.isFinite(reset)
) {
return null;
}
return { resource, limit, remaining, resetAtMs: reset * 1_000 };
}
/**
* Keeps the last tenth of each GitHub quota for interactive requests. A background sweep that
* would dip below it is refused until the quota resets, so a user's next click still has budget.
*
* The balance is GitHub's own count from the latest answer's headers, so it already includes
* what anything else spent with the same token, such as an agent's `gh` commands. Requests in
* flight together all see that one balance; the reserve absorbs what they spend before their
* answers land. Nothing is debited locally, because a 304 or a request that never reached GitHub
* spends nothing, and a local count would drift below GitHub's for the rest of the window.
*
* Interactive requests may spend the reserve, but not a quota GitHub already reported empty.
*/
export class GitHubQuota extends Context.Service<
GitHubQuota,
{
readonly admit: (
host: string,
resource: GitHubQuotaResource,
options?: { readonly allowReserve: boolean },
) => Effect.Effect<void, SourceControlRateLimit.SourceControlRateLimitPausedError>;
readonly observe: (
host: string,
headers: Readonly<Record<string, string | undefined>>,
) => Effect.Effect<void>;
}
>()("@t3tools/source-control-github/server/GitHubQuota") {}
const make = Effect.gen(function* () {
const snapshots = yield* Ref.make<ReadonlyMap<string, QuotaSnapshot>>(new Map());
const keyOf = (host: string, resource: string, scope: string) =>
`${host.trim().toLowerCase()}\0${resource}\0${scope}`;
const admit: GitHubQuota["Service"]["admit"] = Effect.fn("GitHubQuota.admit")(
function* (host, resource, options) {
const now = yield* Clock.currentTimeMillis;
const key = keyOf(host, resource, yield* SourceControlRateLimit.CredentialScope);
const snapshot = (yield* Ref.get(snapshots)).get(key);
if (snapshot === undefined || snapshot.resetAtMs <= now) return;
const floor = options?.allowReserve === true ? 1 : snapshot.limit * RESERVE_RATIO;
if (snapshot.remaining >= floor) return;
return yield* new SourceControlRateLimit.SourceControlRateLimitPausedError({
provider: "github",
host: host.trim().toLowerCase(),
retryAt: snapshot.resetAtMs,
});
},
);
const observe: GitHubQuota["Service"]["observe"] = Effect.fn("GitHubQuota.observe")(
function* (host, headers) {
const quota = quotaFromHeaders(headers);
if (quota === null) return;
const key = keyOf(host, quota.resource, yield* SourceControlRateLimit.CredentialScope);
yield* Ref.update(snapshots, (current) => {
const previous = current.get(key);
// The latest answer wins. GitHub serves requests from several regions, so a later answer
// can report more left in the same window, and keeping the lower one would hold
// background work at the reserve until the reset. An answer from an older window says
// nothing of this one.
if (previous !== undefined && quota.resetAtMs < previous.resetAtMs) return current;
const next = new Map(current);
next.set(key, {
limit: quota.limit,
remaining: quota.remaining,
resetAtMs: quota.resetAtMs,
});
return next;
});
},
);
return GitHubQuota.of({ admit, observe });
});
export const layer = Layer.effect(GitHubQuota, make);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,20 @@
/**
* The GitHub driver: repository operations and discovery through `gh` and git, and pull requests
* through the GitHub REST and GraphQL APIs.
*
* @module source-control-github/server/driver
*/
import { defineSourceControlDriver } from "@t3tools/source-control-core/server/driver";
import * as Effect from "effect/Effect";
import * as GitHubPullRequestProvider from "./GitHubPullRequestProvider.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
export const driver = defineSourceControlDriver({
kind: "github",
make: Effect.all({
sourceControl: GitHubSourceControlProvider.make,
discovery: GitHubSourceControlProvider.makeDiscovery,
pullRequests: GitHubPullRequestProvider.make,
}),
});
@@ -0,0 +1,103 @@
import type { GitHubSettings } from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
const GitHubAuthStatusAccountSchema = Schema.Struct({
state: Schema.String,
error: Schema.optional(Schema.String),
active: Schema.Boolean,
host: Schema.String,
login: Schema.String,
tokenSource: Schema.optional(Schema.String),
});
const GitHubAuthStatusSchema = Schema.Struct({
hosts: Schema.Record(Schema.String, Schema.Array(GitHubAuthStatusAccountSchema)),
});
const decodeGitHubAuthStatusJson = Schema.decodeUnknownOption(
Schema.fromJsonString(GitHubAuthStatusSchema),
);
export interface GitHubAuthStatusAccount {
readonly host: string;
readonly account: string;
readonly authenticated: boolean;
readonly active: boolean;
readonly error: string | null;
/** The variable (GH_TOKEN and kin) the login came from; it overrides every stored login. */
readonly environmentVariable: string | null;
}
export interface GitHubAuthStatus {
readonly parsed: boolean;
readonly accounts: ReadonlyArray<GitHubAuthStatusAccount>;
}
const ENVIRONMENT_TOKEN_SOURCE = /^(?:GH|GITHUB)_(?:ENTERPRISE_)?TOKEN$/u;
function nonEmptyString(value: string): string | null {
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function parseGitHubAuthStatus(text: string): GitHubAuthStatus {
return Option.match(decodeGitHubAuthStatusJson(text), {
onNone: () => ({ parsed: false, accounts: [] }),
onSome: (status) =>
({
parsed: true,
accounts: Object.values(status.hosts).flatMap((accounts) =>
accounts.flatMap((account) => {
const host = nonEmptyString(account.host);
const login = nonEmptyString(account.login);
if (host === null || login === null) return [];
return [
{
host: host.toLowerCase(),
account: login,
authenticated: account.state === "success",
active: account.active,
error: account.error?.trim() || null,
environmentVariable: ENVIRONMENT_TOKEN_SOURCE.test(account.tokenSource ?? "")
? (account.tokenSource ?? null)
: null,
},
];
}),
),
}) satisfies GitHubAuthStatus,
});
}
export function findAuthenticatedGitHubAccount(
accounts: ReadonlyArray<GitHubAuthStatusAccount>,
): GitHubAuthStatusAccount | undefined {
return (
accounts.find((account) => account.authenticated && account.active) ??
accounts.find((account) => account.authenticated)
);
}
/**
* The login GitHub requests for a host will use, honoring Settings: an environment token
* first (gh's own precedence), then the pinned account, then gh's active login.
* Returns undefined when the host is turned off or has no usable login.
*/
export function effectiveGitHubAccount(
host: string,
accounts: ReadonlyArray<GitHubAuthStatusAccount>,
settings: GitHubSettings,
): GitHubAuthStatusAccount | undefined {
const choice = settings.hosts[host];
if (choice?.enabled === false) return undefined;
const usable = accounts.filter((account) => account.host === host && account.authenticated);
return (
usable.find((account) => account.environmentVariable !== null) ??
(choice?.account === undefined
? undefined
: usable.find((account) => account.account === choice.account)) ??
findAuthenticatedGitHubAccount(usable)
);
}
@@ -0,0 +1,245 @@
import { expect, it } from "@effect/vitest";
import * as TestClock from "effect/testing/TestClock";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Redacted from "effect/Redacted";
import type { PullRequestCheck } from "@t3tools/contracts";
import * as GitHubApi from "./GitHubApi.ts";
import { KnownWorkflowRuns, makeChecksRevalidator } from "./gitHubConditionalChecks.ts";
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const reference = { cwd: "/repo", repository: "acme/web", host: "github.com", number: 1 };
const credential = {
host: "github.com",
token: Redacted.make("token"),
credentialFingerprint: "one",
};
it.effect(
"reuses unchanged checks and catches reruns, later pages, fork approvals, pushes and account changes",
() =>
Effect.gen(function* () {
let sha = "a".repeat(40);
let changed = "";
let reads = 0;
const requests: string[] = [];
const known: Array<unknown> = [];
const revalidate = yield* makeChecksRevalidator.pipe(
Effect.provide(
Layer.mock(GitHubApi.GitHubApi)({
rest: ({ path, ifNoneMatch }) =>
Effect.sync(() => {
requests.push(path);
const head = path.endsWith("/pulls/1");
const modified =
ifNoneMatch === undefined || (path.includes(changed) && changed !== "");
const next = path.includes("check-runs") && path.endsWith("page=1");
const runs = path.includes("/actions/runs");
return {
status: modified ? 200 : 304,
headers: modified
? {
etag: `"${sha}-${changed}"`,
...(next ? { link: '<https://api.github.com/next>; rel="next"' } : {}),
}
: {},
body: !modified
? ""
: head
? encodeJson({ head: { sha, repo: { id: 2 } }, base: { repo: { id: 1 } } })
: runs
? encodeJson({
workflow_runs: [
{ id: 9, status: "completed", conclusion: "action_required" },
],
})
: "{}",
truncated: false,
invalidUtf8: false,
};
}),
}),
),
);
const read = Effect.gen(function* () {
known.push(yield* KnownWorkflowRuns);
reads++;
return {
state: "open" as const,
checks: [
{ name: "build", status: "success", description: null, url: null },
] satisfies PullRequestCheck[],
headSha: sha,
workflowApprovalsRequired: 0,
};
});
const poll = (identity = credential) =>
revalidate(reference, read).pipe(
Effect.provideService(GitHubApi.PinnedGitHubCredential, identity),
);
yield* poll();
expect(reads).toBe(1);
// The fork's runs were just confirmed, so the read is handed them instead of listing them.
expect(known[0]).toEqual({
headSha: sha,
runs: [{ id: 9, status: "completed", conclusion: "action_required" }],
});
requests.length = 0;
yield* poll();
expect(reads).toBe(1);
expect(requests).toHaveLength(5);
for (const endpoint of [
"check-runs?filter=all&per_page=100&page=2",
"/status",
"/actions/runs",
"/pulls/1",
]) {
changed = endpoint;
yield* poll();
changed = "";
yield* poll();
}
expect(reads).toBe(5);
sha = "b".repeat(40);
changed = "/pulls/1";
requests.length = 0;
yield* poll();
expect(reads).toBe(6);
expect(
requests
.filter((endpoint) => endpoint.includes("/commits/"))
.every((endpoint) => endpoint.includes(sha)),
).toBe(true);
changed = "";
yield* poll({ ...credential, credentialFingerprint: "two" });
expect(reads).toBe(7);
yield* TestClock.adjust("5 minutes");
yield* poll();
expect(reads).toBe(8);
}),
);
it.effect("does not retain failed or incomplete reads, and supports hosts without ETags", () =>
Effect.gen(function* () {
const sha = "a".repeat(40);
let etags = true;
let unavailable = false;
let fail = true;
let complete = true;
let reads = 0;
const revalidate = yield* makeChecksRevalidator.pipe(
Effect.provide(
Layer.mock(GitHubApi.GitHubApi)({
rest: ({ path, ifNoneMatch }) =>
unavailable
? Effect.fail(
new GitHubApi.GitHubApiResponseError({
host: "github.com",
operation: "revalidateChecks",
status: 502,
}),
)
: Effect.succeed(
ifNoneMatch !== undefined && etags
? { status: 304, headers: {}, body: "", truncated: false, invalidUtf8: false }
: {
status: 200,
headers: etags ? { etag: '"one"' } : {},
body: path.endsWith("/pulls/1")
? encodeJson({
head: { sha, repo: { id: 1 } },
base: { repo: { id: 1 } },
})
: "{}",
truncated: false,
invalidUtf8: false,
},
),
}),
),
);
const read = Effect.suspend(() => {
reads++;
return fail
? Effect.fail(
new GitHubApi.GitHubApiResponseError({
host: "github.com",
operation: "read",
status: 500,
}),
)
: Effect.succeed({
state: "open" as const,
checks: [],
headSha: sha,
...(complete ? { workflowApprovalsRequired: 0 } : {}),
});
});
const poll = () =>
revalidate(reference, read).pipe(
Effect.provideService(GitHubApi.PinnedGitHubCredential, credential),
);
yield* poll().pipe(Effect.flip);
fail = false;
complete = false;
yield* poll();
yield* poll();
expect(reads).toBe(3);
complete = true;
yield* poll();
yield* poll();
expect(reads).toBe(4);
yield* TestClock.adjust("5 minutes");
complete = false;
yield* poll();
yield* poll();
expect(reads).toBe(6);
complete = true;
unavailable = true;
yield* poll();
expect(reads).toBe(7);
unavailable = false;
yield* poll();
yield* poll();
expect(reads).toBe(8);
etags = false;
yield* poll();
yield* poll();
expect(reads).toBe(10);
}),
);
it.effect("falls back when REST checks are unavailable without retrying unsupported probes", () =>
Effect.gen(function* () {
let probes = 0;
let reads = 0;
const revalidate = yield* makeChecksRevalidator.pipe(
Effect.provide(
Layer.mock(GitHubApi.GitHubApi)({
rest: () => {
probes++;
return Effect.fail(
new GitHubApi.GitHubApiNotFoundError({
host: "github.com",
operation: "revalidateChecks",
}),
);
},
}),
),
);
const read = Effect.sync(() => {
reads++;
return { state: "open" as const, checks: [] };
});
for (let tick = 0; tick < 2; tick++)
yield* revalidate(reference, read).pipe(
Effect.provideService(GitHubApi.PinnedGitHubCredential, credential),
);
expect(probes).toBe(1);
expect(reads).toBe(2);
}),
);
@@ -0,0 +1,195 @@
import * as Clock from "effect/Clock";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { PositiveInt, type PullRequestChecks } from "@t3tools/contracts";
import * as GitHubApi from "./GitHubApi.ts";
import type { GitHubPullRequestDetail } from "./gitHubPullRequestJson.ts";
import type { GitHubPullRequestApiError } from "./GitHubPullRequestApi.ts";
import type { ProviderRepositoryRef } from "@t3tools/source-control-core/server/PullRequestProvider";
const HeadSchema = Schema.Struct({
head: Schema.Struct({
sha: Schema.String.check(Schema.isPattern(/^[a-f0-9]{40,64}$/)),
// Null once the fork a pull request came from has been deleted.
repo: Schema.NullOr(Schema.Struct({ id: PositiveInt })),
}),
base: Schema.Struct({ repo: Schema.Struct({ id: PositiveInt }) }),
});
const decodeHead = Schema.decodeUnknownEffect(Schema.fromJsonString(HeadSchema));
const WorkflowRunSchema = Schema.Struct({
id: Schema.Int,
name: Schema.optional(Schema.NullOr(Schema.String)),
html_url: Schema.optional(Schema.NullOr(Schema.String)),
status: Schema.optional(Schema.NullOr(Schema.String)),
conclusion: Schema.optional(Schema.NullOr(Schema.String)),
head_branch: Schema.optional(Schema.NullOr(Schema.String)),
});
const decodeWorkflowRuns = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Struct({ workflow_runs: Schema.Array(WorkflowRunSchema) })),
);
export type KnownWorkflowRun = typeof WorkflowRunSchema.Type;
/**
* Every `pull_request` workflow run of one head, as the revalidator just confirmed them against
* GitHub. A read running under it filters these rather than asking for the runs again.
*/
export const KnownWorkflowRuns = Context.Reference<{
readonly headSha: string;
readonly runs: ReadonlyArray<KnownWorkflowRun>;
} | null>("@t3tools/source-control-github/server/gitHubConditionalChecks/KnownWorkflowRuns", {
defaultValue: () => null,
});
type Validator = { etag: string | undefined; next: boolean; body: string };
/** A host that answers these with one of them has no conditional REST for it at all. */
const UNSUPPORTED_STATUSES = new Set([404, 405, 501]);
export const makeChecksRevalidator = Effect.gen(function* () {
const api = yield* GitHubApi.GitHubApi;
const entries = yield* Cache.makeWith(
(_key: string) =>
Effect.sync(() => ({
gate: Semaphore.makeUnsafe(1),
validators: new Map<string, Validator>(),
head: null as typeof HeadSchema.Type | null,
value: null as PullRequestChecks | null,
readAt: 0,
supported: true,
})),
{ capacity: 128, timeToLive: () => "30 minutes" },
);
return (
input: ProviderRepositoryRef & { readonly number: number },
read: Effect.Effect<
Pick<GitHubPullRequestDetail, "state" | "checks" | "headSha"> & {
workflowApprovalsRequired?: number;
},
GitHubPullRequestApiError
>,
) =>
Effect.gen(function* () {
const credential = yield* GitHubApi.PinnedGitHubCredential;
if (credential === null) return yield* read;
const key = `${credential.credentialFingerprint}\0${input.host}\0${input.repository}\0${input.number}`;
const entry = yield* Cache.get(entries, key);
return yield* entry.gate.withPermit(
Effect.gen(function* () {
if (!entry.supported) return yield* read;
const fail = (status: number) =>
new GitHubApi.GitHubApiResponseError({
host: input.host,
operation: "revalidateChecks",
status,
});
/** Whether the endpoint has a next page, or null where the host cannot say. */
const get = (endpoint: string, head = false) =>
Effect.gen(function* () {
const previous = entry.validators.get(endpoint);
const response = yield* api
.rest({
host: input.host,
operation: "revalidateChecks",
path: endpoint,
...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
})
.pipe(
Effect.catchTags({
GitHubApiNotFoundError: () =>
Effect.sync(() => {
entry.supported = false;
return null;
}),
GitHubApiResponseError: (error) =>
Effect.sync(() => {
entry.supported = !UNSUPPORTED_STATUSES.has(error.status);
return null;
}),
}),
);
if (response === null) {
entry.value = null;
return null;
}
if (response.status === 304 && previous) return previous.next;
if (response.status !== 200 || response.truncated) {
return yield* fail(response.status);
}
entry.value = null;
if (head) {
const decoded = yield* decodeHead(response.body).pipe(
Effect.mapError(() => fail(response.status)),
);
if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
entry.head = decoded;
}
const validator = {
etag: response.headers["etag"]?.trim(),
next: /rel="next"/.test(response.headers["link"] ?? ""),
body: response.body,
};
entry.validators.set(endpoint, validator);
return validator.next;
});
const root = `repos/${input.repository}`;
if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
const head = entry.head;
if (head === null) return yield* fail(200);
const runsEndpoint =
head.head.repo?.id !== head.base.repo.id
? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`
: null;
const endpoints = [
`${root}/commits/${head.head.sha}/check-runs?filter=all`,
`${root}/commits/${head.head.sha}/status`,
...(runsEndpoint === null ? [] : [runsEndpoint]),
];
const runPages: Array<string> = [];
for (const endpoint of endpoints) {
for (let page = 1; ; page++) {
if (page > 100) return yield* fail(200);
const paged = `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`;
const next = yield* get(paged);
if (next === null) return yield* read;
if (endpoint === runsEndpoint) runPages.push(paged);
if (!next) break;
}
}
const now = yield* Clock.currentTimeMillis;
if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
// Every page of the head's runs was just confirmed current, so the read filters them
// rather than listing the runs a second time.
const pages = runPages.map((endpoint) =>
decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""),
);
const known =
runsEndpoint !== null && pages.every(Option.isSome)
? {
headSha: head.head.sha,
runs: pages.flatMap((page) =>
Option.isSome(page) ? page.value.workflow_runs : [],
),
}
: null;
const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known));
const value = {
state: fresh.state,
checks: fresh.checks,
};
entry.value =
fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha
? value
: null;
entry.readAt = now;
return value;
}),
);
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,145 @@
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
export interface NormalizedGitHubPullRequestRecord {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
/** The head commit, when the read asked for `headRefOid`. */
readonly headSha?: string;
readonly state: "open" | "closed" | "merged";
readonly isDraft?: boolean;
readonly closedAt?: string | null;
readonly mergedAt?: string | null;
readonly updatedAt: Option.Option<DateTime.Utc>;
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
const GitHubPullRequestSchema = Schema.Struct({
number: PositiveInt,
title: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
baseRefName: TrimmedNonEmptyString,
headRefName: TrimmedNonEmptyString,
headRefOid: Schema.optional(Schema.NullOr(Schema.String)),
state: Schema.optional(Schema.NullOr(Schema.String)),
isDraft: Schema.optional(Schema.Boolean),
closedAt: Schema.optional(Schema.NullOr(Schema.String)),
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
isCrossRepository: Schema.optional(Schema.Boolean),
// gh < 2.47 exports headRepository as {id, name} only; nameWithOwner was
// added later. Both fields stay optional so a version-drifted gh CLI can
// never fail the decode and silently drop the PR from the list.
headRepository: Schema.optional(
Schema.NullOr(
Schema.Struct({
nameWithOwner: Schema.optional(Schema.NullOr(Schema.String)),
name: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
),
headRepositoryOwner: Schema.optional(
Schema.NullOr(
Schema.Struct({
login: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
),
});
function trimOptionalString(value: string | null | undefined): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function normalizeGitHubPullRequestState(input: {
state?: string | null | undefined;
mergedAt?: string | null | undefined;
}): "open" | "closed" | "merged" {
const normalizedState = input.state?.trim().toUpperCase();
if (
(typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) ||
normalizedState === "MERGED"
) {
return "merged";
}
if (normalizedState === "CLOSED") {
return "closed";
}
return "open";
}
function normalizeGitHubPullRequestRecord(
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
): NormalizedGitHubPullRequestRecord {
const explicitNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
const headRepositoryName = trimOptionalString(raw.headRepository?.name);
const headRepositoryOwnerLogin =
trimOptionalString(raw.headRepositoryOwner?.login) ??
(explicitNameWithOwner?.includes("/") ? (explicitNameWithOwner.split("/")[0] ?? null) : null);
const headRepositoryNameWithOwner =
explicitNameWithOwner ??
(headRepositoryOwnerLogin && headRepositoryName
? `${headRepositoryOwnerLogin}/${headRepositoryName}`
: null);
const headSha = trimOptionalString(raw.headRefOid);
return {
number: raw.number,
title: raw.title,
url: raw.url,
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
...(headSha ? { headSha } : {}),
state: normalizeGitHubPullRequestState(raw),
...(raw.isDraft === true ? { isDraft: true } : {}),
closedAt: raw.closedAt ?? null,
mergedAt: raw.mergedAt ?? null,
updatedAt: raw.updatedAt ?? Option.none(),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
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>
> {
return Result.map(decodeGitHubPullRequestList(raw), decodeGitHubPullRequestEntries);
}
@@ -0,0 +1,87 @@
import { assert, describe, it } from "@effect/vitest";
import {
gitHubApiHostForRemote,
selectGitHubBaseRepository,
} from "./gitHubRepositoryResolution.ts";
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 }) =>
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("gitHubApiHostForRemote", () => {
it("reads an SSH alias through github.com and a real host as itself", () => {
assert.strictEqual(gitHubApiHostForRemote("git@github:acme/web.git"), "github.com");
assert.strictEqual(
gitHubApiHostForRemote("[email protected]:a/b.git"),
"github.example.com",
);
assert.strictEqual(gitHubApiHostForRemote("[email protected]:a/b.git"), null);
});
});
@@ -0,0 +1,192 @@
import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
import {
detectSourceControlProviderFromRemoteUrl,
isSshRemoteUrl,
} from "@t3tools/shared/sourceControl";
/** A repository on a GitHub host: the API it is read through, and its owner and name. */
export interface GitHubRepositoryLocator {
readonly host: string;
readonly owner: string;
readonly name: string;
}
/** The fetch remotes in `git remote -v` output, by name. */
export function parseFetchRemotes(
remotes: string,
): ReadonlyArray<{ readonly name: string; readonly url: string }> {
return remotes
.split("\n")
.map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim()))
.filter((match): match is RegExpExecArray => match !== null)
.map((match) => ({ name: match[1]!, url: match[2]! }));
}
/**
* 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
* fall back to the provider's remote, then to the best-ranked remote on the host.
*/
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 remote of parseFetchRemotes(input.remotes)) {
const [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/");
if (remoteHost !== host || !owner || !name || rest.length > 0) return null;
repositories.set(remote.name, { 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;
}
/**
* The repository `gh` would act on in a checkout, from its remotes: the remote `gh` would pick,
* else the best-ranked remote on the host. `host` is the API host it settled on, which a caller
* names when no repository was found there. GH_REPO is the caller's to check first.
*/
export function resolveGitHubRepository(input: {
readonly remotes: string;
readonly resolved: string;
/** The checkout's GitHub API host, when the caller already knows it. */
readonly hostHint: string | undefined;
readonly defaultHost: string;
}): { readonly host: string; readonly locator: GitHubRepositoryLocator | null } {
const fetchRemotes = parseFetchRemotes(input.remotes).map((remote) => ({
...remote,
host: gitHubApiHostForRemote(remote.url),
}));
const host =
(input.hostHint === undefined ? undefined : apiHostForHint(input.hostHint)) ??
fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??
fetchRemotes.find((remote) => remote.host !== null)?.host ??
input.defaultHost;
const selected = selectGitHubBaseRepository({
remotes: input.remotes,
resolved: input.resolved,
host,
});
if (selected !== null) return { host, locator: { host, ...selected } };
// gh's own order without its prompt: upstream, github, origin, then the first remote, among
// the ones on this host (an SSH alias counts as its API host).
const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
const candidates = fetchRemotes
.filter(
(remote) => remote.host === host || normalizeGitRemoteUrl(remote.url).split("/")[0] === host,
)
.toSorted((left, right) => {
const l = rank(left.name);
const r = rank(right.name);
return (l === -1 ? 99 : l) - (r === -1 ? 99 : r);
});
for (const remote of candidates) {
const [owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/").slice(1);
if (owner && name && rest.length === 0) return { host, locator: { host, owner, name } };
}
return { host, locator: null };
}
/** `owner/name` or `host/owner/name`, as `gh --repo` and GH_REPO take them. */
export function parseGitHubRepositorySelector(
selector: string,
defaultHost: string,
): GitHubRepositoryLocator | null {
const trimmed = selector.trim().replace(/\.git$/i, "");
if (/^https?:\/\//i.test(trimmed)) {
try {
const url = new URL(trimmed);
const [owner, name, ...rest] = url.pathname.split("/").filter(Boolean);
return owner && name && rest.length === 0
? { host: url.host.toLowerCase(), owner, name }
: null;
} catch {
return null;
}
}
const parts = trimmed.split("/").filter(Boolean);
if (parts.length === 2) return { host: defaultHost, owner: parts[0]!, name: parts[1]! };
if (parts.length === 3)
return { host: parts[0]!.toLowerCase(), owner: parts[1]!, name: parts[2]! };
return null;
}
/**
* A pull request reference the way `gh pr view` takes one: a number (`#7` too), a pull request
* URL, or a branch name.
*/
export function parsePullRequestReference(
reference: string,
):
| { readonly kind: "number"; readonly number: number }
| { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }
| { readonly kind: "branch"; readonly headSelector: string } {
const trimmed = reference.trim();
const numbered = /^#?([1-9]\d*)$/.exec(trimmed);
if (numbered) return { kind: "number", number: Number(numbered[1]) };
if (/^https?:\/\//i.test(trimmed)) {
try {
const url = new URL(trimmed);
const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);
if (match) {
return {
kind: "url",
locator: { host: url.host.toLowerCase(), owner: match[1]!, name: match[2]! },
number: Number(match[3]),
};
}
} catch {
// Not a URL after all; read it as a branch.
}
}
return { kind: "branch", headSelector: trimmed };
}
/**
* The GitHub host a remote URL is served from, or null for a remote that is not GitHub. An SSH
* alias (`git@github-work:owner/repo`) names no API host of its own; it is read through
* `github.com`, which is what such an alias almost always stands for (issue #6198).
*/
export function gitHubApiHostForRemote(remoteUrl: string): string | null {
const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
if (provider === null) return null;
const host = new URL(provider.baseUrl).host.toLowerCase();
// A dotless SSH host is an alias from ~/.ssh/config, never a real API host.
if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {
return host.includes("github") ? "github.com" : null;
}
return provider.kind === "github" ? host : null;
}
/** A caller's host hint, read the way a remote's host is: a dotless alias is not an API host. */
function apiHostForHint(host: string): string {
const normalized = host.toLowerCase();
return !normalized.includes(".") && normalized.includes("github") ? "github.com" : normalized;
}
@@ -0,0 +1,105 @@
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { aliasedGraphQlDocument, readGraphQlPages } from "./githubGraphQl.ts";
describe("aliasedGraphQlDocument", () => {
it("keeps every value out of the document, each under its alias's own variable", () => {
const document = aliasedGraphQlDocument({
operation: "query",
name: "Lookups",
alias: "s",
items: ['acme") { x } #', "web"],
shared: { owner: ["String!", "acme"] },
variables: (repo) => ({ name: ["String!", repo] }),
field: ({ name }) => `repository(owner: $owner, name: ${name}) { id }`,
});
assert.isNotNull(document);
expect(document!.query).toBe(
"query Lookups($owner: String!, $s0_name: String!, $s1_name: String!) {\n" +
" s0: repository(owner: $owner, name: $s0_name) { id }\n" +
" s1: repository(owner: $owner, name: $s1_name) { id }\n}",
);
expect(document!.variables).toEqual({
owner: "acme",
s0_name: 'acme") { x } #',
s1_name: "web",
});
});
it("aliases by key and nests inside a shared parent when asked", () => {
const document = aliasedGraphQlDocument({
operation: "query",
alias: "pr",
key: (number) => number,
items: [2, 3],
variables: (number) => ({ number: ["Int!", number] }),
field: ({ number }) => `pullRequest(number: ${number}) { id }`,
within: (fields) => `repository(owner: "a", name: "b") {\n${fields}\n}`,
});
expect(document?.query).toContain(" pr2: pullRequest(number: $pr2_number) { id }");
expect(document?.query).toContain(" pr3: pullRequest(number: $pr3_number) { id }");
expect(document?.variables).toEqual({ pr2_number: 2, pr3_number: 3 });
});
it("asks for nothing when there is nothing to ask", () => {
expect(
aliasedGraphQlDocument({
operation: "mutation",
alias: "f",
items: [],
variables: () => ({}),
field: () => "x",
}),
).toBeNull();
});
});
describe("readGraphQlPages", () => {
const pages = (cursors: ReadonlyArray<string | null>) => {
const asked: Array<string | null> = [];
const read = (after: string | null) =>
Effect.sync(() => {
asked.push(after);
return { next: cursors[asked.length - 1] ?? null };
});
return { asked, read };
};
it.effect("follows the cursor until GitHub has no more", () =>
Effect.gen(function* () {
const { asked, read } = pages(["a", "b", null]);
const result = yield* readGraphQlPages(read, { nextCursor: (page) => page.next });
expect(asked).toEqual([null, "a", "b"]);
expect(result.truncated).toBe(false);
}),
);
it.effect("stops as truncated at the page limit, at `until`, or on a repeated cursor", () =>
Effect.gen(function* () {
const limited = pages(["a", "b", "c"]);
const atLimit = yield* readGraphQlPages(limited.read, {
nextCursor: (page) => page.next,
maxPages: 2,
});
expect(limited.asked).toEqual([null, "a"]);
expect(atLimit.truncated).toBe(true);
const enough = pages(["a", "b", "c"]);
const satisfied = yield* readGraphQlPages(enough.read, {
nextCursor: (page) => page.next,
until: (read) => read.length === 1,
});
expect(enough.asked).toEqual([null]);
expect(satisfied.truncated).toBe(true);
const stuck = pages(["a", "a", "a"]);
const repeated = yield* readGraphQlPages(stuck.read, {
nextCursor: (page) => page.next,
from: "start",
});
expect(stuck.asked).toEqual(["start", "a"]);
expect(repeated.truncated).toBe(true);
}),
);
});
@@ -0,0 +1,100 @@
import * as Effect from "effect/Effect";
/** GraphQL variables by name, each with the type it is declared as and the value it carries. */
export type GraphQlVariables = Readonly<Record<string, readonly [type: string, value: unknown]>>;
export interface GraphQlDocument {
readonly query: string;
readonly variables: Readonly<Record<string, unknown>>;
}
/**
* One document asking the same field for many items, each under its own alias: the prefix and
* the item's position (`s0`, `s1`, …), or its `key` when the answer is easier read by one. GitHub
* has no bulk form of most lookups, so aliases are how a batch travels in one request.
*
* Every value travels as a variable renamed per alias (`$s0_owner`), and `field` is handed those
* placeholders rather than the values: nothing an item holds is written into the document.
* `shared` variables are declared once and referenced by their own name; `within` nests the aliased
* fields inside one parent selection, such as a single repository.
*
* Null for no items, since a document with no selection is not a document.
*/
export function aliasedGraphQlDocument<Item, Variables extends GraphQlVariables>(input: {
readonly operation: "query" | "mutation";
/** The operation's name, which tells one batch from another in logs and recorded traffic. */
readonly name?: string;
readonly alias: string;
readonly key?: (item: Item, index: number) => number;
readonly items: ReadonlyArray<Item>;
readonly variables: (item: Item) => Variables;
readonly field: (
placeholders: { readonly [Name in keyof Variables]: string },
item: Item,
) => string;
readonly shared?: GraphQlVariables;
readonly within?: (fields: string) => string;
}): GraphQlDocument | null {
if (input.items.length === 0) return null;
const declarations: string[] = [];
const variables: Record<string, unknown> = {};
for (const [name, [type, value]] of Object.entries(input.shared ?? {})) {
declarations.push(`$${name}: ${type}`);
variables[name] = value;
}
const fields = input.items.map((item, index) => {
const alias = `${input.alias}${input.key?.(item, index) ?? index}`;
const placeholders: Record<string, string> = {};
for (const [name, [type, value]] of Object.entries(input.variables(item))) {
const variable = `${alias}_${name}`;
declarations.push(`$${variable}: ${type}`);
variables[variable] = value;
placeholders[name] = `$${variable}`;
}
return ` ${alias}: ${input.field(placeholders as { readonly [Name in keyof Variables]: string }, item)}`;
});
const selection = fields.join("\n");
const parameters = declarations.length === 0 ? "" : `(${declarations.join(", ")})`;
return {
query: `${input.operation}${input.name === undefined ? "" : ` ${input.name}`}${parameters} {\n${input.within?.(selection) ?? selection}\n}`,
variables,
};
}
/**
* The pages of a GraphQL connection, read one after another from `from` (the first page by
* default) until GitHub has no more, `until` is satisfied, or `maxPages` have been read. `read` is
* handed the pages so far, for reads that size or check the next page by what has already arrived.
*
* `truncated` says pages remained when reading stopped. A cursor GitHub hands back a second time
* would page forever, so it stops the read as truncated too.
*/
export const readGraphQlPages = <Page, E, R>(
read: (after: string | null, pages: ReadonlyArray<Page>) => Effect.Effect<Page, E, R>,
options: {
readonly nextCursor: (page: NoInfer<Page>) => string | null;
readonly from?: string | null;
readonly maxPages?: number;
readonly until?: (pages: ReadonlyArray<NoInfer<Page>>) => boolean;
},
): Effect.Effect<{ readonly pages: ReadonlyArray<Page>; readonly truncated: boolean }, E, R> =>
Effect.gen(function* () {
const pages: Page[] = [];
const seen = new Set<string>();
let after = options.from ?? null;
while (true) {
const page: Page = yield* read(after, pages);
pages.push(page);
const next = options.nextCursor(page);
if (next === null) return { pages, truncated: false };
if (
seen.has(next) ||
pages.length >= (options.maxPages ?? Infinity) ||
options.until?.(pages) === true
) {
return { pages, truncated: true };
}
seen.add(next);
after = next;
}
});
@@ -0,0 +1,395 @@
import { expect, it } from "@effect/vitest";
import * as Layer from "effect/Layer";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as FileSystem from "effect/FileSystem";
import * as Redacted from "effect/Redacted";
import { ChildProcessSpawner } from "effect/process";
import * as GitHubApi from "./GitHubApi.ts";
import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
/**
* One request as the fake saw it, flattened to words: the path or document, then each variable
* or body field as `name=value`, so an assertion reads as "this request carried that value".
*/
type Call = ReadonlyArray<string>;
type Send = (
call: Call,
kind: "graphql" | "rest",
) => Effect.Effect<string, GitHubApi.GitHubApiError>;
/** Every git command the cascade ran, in order; none actually runs. */
let gitCalls: Array<ReadonlyArray<string>> = [];
const fakeGit = Layer.mergeAll(
TestSourceControlHost.layer({
process: {
run: (input) =>
Effect.sync(() => {
gitCalls.push(input.args);
const stdout =
input.args[0] === "rev-parse" || input.args[0] === "merge-base" ? "new-sha\n" : "";
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}),
},
}),
FileSystem.layerNoop({ makeTempDirectoryScoped: () => Effect.succeed("/tmp/scratch") }),
);
const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackAction>[0]) =>
runStackAction(input).pipe(
Effect.provide(
Layer.mergeAll(
fakeGit,
Layer.mock(GitHubApi.GitHubApi)({
credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
graphql: (request) => {
// GitHub refuses a document that declares a variable it never uses.
const declared = [...request.query.matchAll(/\$(\w+)\s*:/g)].map((match) => match[1]!);
const unused = declared.filter(
(name) => !new RegExp(`\\$${name}(?!\\w)(?!\\s*:)`).test(request.query),
);
if (unused.length > 0) {
return Effect.die(new Error(`Variables declared but not used: ${unused.join(", ")}`));
}
return send(words(request.query, request.variables), "graphql");
},
rest: (request) =>
send(words(request.path, request.body), "rest").pipe(
Effect.map((body) => ({
status: 200,
headers: {},
body,
truncated: false,
invalidUtf8: false,
})),
),
}),
),
),
);
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
function words(head: string, fields: unknown): Call {
return [
head,
...Object.entries((fields ?? {}) as Record<string, unknown>).map(
([key, value]) => `${key}=${typeof value === "string" ? value : encodeJson(value)}`,
),
];
}
const isMutation = (call: Call) => call[0]!.startsWith("mutation");
const stack = [
{
number: 50,
url: "https://api.github.com/repos/acme/web/stacks/50",
base: { ref: "main" },
pull_requests: [
{
number: 1,
title: "Base",
head: { ref: "base", sha: "aaa" },
state: "closed",
merged_at: "2026-01-01T00:00:00Z",
},
{
number: 2,
title: "Middle",
head: { ref: "middle", sha: "bbb" },
state: "open",
draft: false,
},
{ number: 3, title: "Top", head: { ref: "top", sha: "ccc" }, state: "open", draft: false },
],
},
];
const input = {
cwd: "/repo",
repository: "acme/web",
host: "github.com",
number: 3,
stackNumber: 50,
expectedStackHeads: [
{ number: 2, headSha: "bbb" },
{ number: 3, headSha: "ccc" },
],
action: "merge" as const,
};
const access = {
data: {
repository: {
pr2: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
pr3: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
},
},
};
const branch = (number: number, headRefOid: string, behindBy = 1, processed: string[] = []) => ({
data: {
processed: processed.map((headRefOid) => ({ headRefOid })),
repository: {
pullRequest: { id: `PR_${number}`, headRefOid, baseRef: { compare: { behindBy } } },
},
},
});
const rebased = {
data: { updatePullRequestBranch: { pullRequest: { headRefOid: "rebased-sha" } } },
};
const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased];
function fake(responses: readonly unknown[]) {
const calls: Call[] = [];
const execute: Send = (call) =>
Effect.sync(() => {
calls.push(call);
const value = responses[calls.length - 1];
if (value === undefined) throw new Error("Unexpected GitHub request");
return encodeJson(value);
});
return { execute, calls };
}
it.effect("submits one atomic merge with the reviewed head and respects the merge queue", () =>
Effect.gen(function* () {
const api = fake([stack, { status: "enqueued", details: {} }]);
yield* runGitHubStackAction(api.execute, { ...input, mergeMethod: "squash" });
expect(api.calls).toHaveLength(2);
expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
expect(api.calls[1]).toContain("sha=ccc");
expect(api.calls[1]).toContain("merge_action=default");
expect(api.calls[1]).toContain("merge_method=squash");
}),
);
it.effect("merges through the selected layer without including later draft layers", () =>
Effect.gen(function* () {
const fiveLayers = [
{
...stack[0],
pull_requests: Array.from({ length: 5 }, (_, index) => ({
number: index + 1,
head: { ref: `layer-${index + 1}`, sha: `sha-${index + 1}` },
state: "open",
draft: index >= 3,
})),
},
];
const api = fake([fiveLayers, { status: "merged", details: {} }]);
yield* runGitHubStackAction(api.execute, {
...input,
number: 3,
expectedStackHeads: [1, 2, 3].map((number) => ({ number, headSha: `sha-${number}` })),
});
expect(api.calls).toHaveLength(2);
expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
expect(api.calls[1]).toContain("sha=sha-3");
expect(api.calls[1]).toContain("merge_action=default");
}),
);
it.effect("rejects stale reviewed heads below a selected middle layer", () =>
Effect.gen(function* () {
const api = fake([stack]);
const result = yield* runGitHubStackAction(api.execute, {
...input,
number: 2,
expectedStackHeads: [{ number: 2, headSha: "old-head" }],
}).pipe(Effect.result);
expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
expect(api.calls).toHaveLength(1);
}),
);
it.effect("does not merge from an already merged layer", () =>
Effect.gen(function* () {
const api = fake([stack]);
const result = yield* runGitHubStackAction(api.execute, {
...input,
number: 1,
expectedStackHeads: [],
}).pipe(Effect.result);
expect(result).toMatchObject({
_tag: "Failure",
failure: { _tag: "GitHubStackUnsupportedError" },
});
expect(api.calls).toHaveLength(1);
}),
);
it.effect("polls an accepted merge and reports a later rule rejection", () =>
Effect.gen(function* () {
const api = fake([
stack,
{ status: "pending", details: { uuid: "operation" } },
{ status: "failed", details: { message: "Required checks have not passed" } },
]);
const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
Effect.result,
Effect.forkChild,
);
yield* TestClock.adjust("1 second");
const result = yield* Fiber.join(fiber);
expect(result).toMatchObject({
_tag: "Failure",
failure: { _tag: "GitHubStackMergeRejectedError" },
});
expect(api.calls[2]).toContain("repos/acme/web/pulls/3/merge-async/operation");
}),
);
it.effect("retains stack identity and a rejection response without a message", () =>
Effect.gen(function* () {
const rejection = { status: "failed", details: {} };
const api = fake([stack, rejection]);
const result = yield* runGitHubStackAction(api.execute, input).pipe(Effect.result);
expect(result).toMatchObject({
_tag: "Failure",
failure: {
_tag: "GitHubStackMergeRejectedError",
repository: input.repository,
number: input.number,
stackNumber: input.stackNumber,
cause: rejection,
},
});
}),
);
it.effect("refuses a changed stack before performing any mutation", () =>
Effect.gen(function* () {
const api = fake([stack]);
const result = yield* runGitHubStackAction(api.execute, {
...input,
expectedStackHeads: [
{ number: 2, headSha: "old" },
{ number: 3, headSha: "ccc" },
],
}).pipe(Effect.result);
expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
expect(api.calls).toHaveLength(1);
}),
);
it.effect("refuses the entire rebase before mutation when a later fork denies write access", () =>
Effect.gen(function* () {
const api = fake([
stack,
{
data: {
repository: {
...access.data.repository,
pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: false },
},
},
},
]);
const result = yield* runGitHubStackAction(api.execute, {
...input,
action: "update-branch",
}).pipe(Effect.result);
expect(result).toMatchObject({
_tag: "Failure",
failure: { _tag: "GitHubStackPermissionError" },
});
expect(api.calls).toHaveLength(2);
}),
);
it.effect("allows a fork that explicitly permits maintainer updates", () =>
Effect.gen(function* () {
const api = fake([
stack,
{
data: {
repository: {
...access.data.repository,
pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: true },
},
},
},
...rebaseResponses,
]);
yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2);
}),
);
it.effect("bounds polling and reports a still-running merge without claiming success", () =>
Effect.gen(function* () {
const api = fake([
stack,
...Array.from({ length: 40 }, () => ({ status: "pending", details: { uuid: "operation" } })),
]);
const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
Effect.result,
Effect.forkChild,
);
yield* TestClock.adjust("6 minutes");
expect(yield* Fiber.join(fiber)).toMatchObject({
_tag: "Failure",
failure: { _tag: "GitHubStackMergePendingError" },
});
expect(api.calls.length).toBeLessThan(40);
}),
);
it.effect("rebases the open layers bottom to top in a scratch clone, each onto the one below", () =>
Effect.gen(function* () {
gitCalls = [];
const api = fake([stack, access]);
yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
// GitHub is only read; every change is a git push with a lease on the reviewed head.
expect(api.calls.some(isMutation)).toBe(false);
const rebases = gitCalls.filter((args) => args[0] === "rebase");
expect(rebases).toEqual([
["rebase", "--quiet", "--onto", "origin/main", "new-sha"],
["rebase", "--quiet", "--onto", "new-sha", "bbb"],
]);
expect(gitCalls.filter((args) => args[0] === "push")).toEqual([
[
"push",
"--quiet",
"--force-with-lease=refs/heads/middle:bbb",
"origin",
"new-sha:refs/heads/middle",
],
[
"push",
"--quiet",
"--force-with-lease=refs/heads/top:ccc",
"origin",
"new-sha:refs/heads/top",
],
]);
}),
);
it.effect("checks every layer's write access before any git runs", () =>
Effect.gen(function* () {
gitCalls = [];
const api = fake([
stack,
{
data: {
repository: {
...access.data.repository,
pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: false },
},
},
},
]);
yield* Effect.flip(runGitHubStackAction(api.execute, { ...input, action: "update-branch" }));
expect(gitCalls).toEqual([]);
}),
);
@@ -0,0 +1,288 @@
import type {
PullRequestAction,
PullRequestMergeMethod,
PullRequestStackHead,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Clock from "effect/Clock";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as GitHubApi from "./GitHubApi.ts";
import { aliasedGraphQlDocument } from "./githubGraphQl.ts";
import { decodePullRequestStacksJson } from "./gitHubPullRequestJson.ts";
import { cascadeRebaseStack } from "./githubStackRebase.ts";
const stackErrorIdentity = {
repository: Schema.String,
number: Schema.Int,
stackNumber: Schema.Int,
};
export class GitHubStackChangedError extends Schema.TaggedError<GitHubStackChangedError>()(
"GitHubStackChangedError",
{ ...stackErrorIdentity, completed: Schema.Int },
) {
override get message(): string {
return this.completed > 0
? `The stack changed at PR #${this.number} after ${this.completed} layers. Earlier updates remain on GitHub. Refresh it before trying again.`
: "The stack changed. Refresh it before trying again.";
}
}
export class GitHubStackUnsupportedError extends Schema.TaggedError<GitHubStackUnsupportedError>()(
"GitHubStackUnsupportedError",
stackErrorIdentity,
) {
override get message(): string {
return "This operation is not supported for this stack.";
}
}
export class GitHubStackResponseInvalidError extends Schema.TaggedError<GitHubStackResponseInvalidError>()(
"GitHubStackResponseInvalidError",
{ ...stackErrorIdentity, cause: Schema.optional(Schema.Defect()) },
) {
override get message(): string {
return "GitHub returned an unreadable stack operation response.";
}
}
export class GitHubStackMergeRejectedError extends Schema.TaggedError<GitHubStackMergeRejectedError>()(
"GitHubStackMergeRejectedError",
{ ...stackErrorIdentity, cause: Schema.Defect() },
) {
override get message(): string {
return "GitHub refused the stack merge. Check the stack's branch rules and merge requirements.";
}
}
export class GitHubStackMergePendingError extends Schema.TaggedError<GitHubStackMergePendingError>()(
"GitHubStackMergePendingError",
stackErrorIdentity,
) {
override get message(): string {
return "The merge is still running on GitHub. Check its status there before submitting another request.";
}
}
export class GitHubStackPermissionError extends Schema.TaggedError<GitHubStackPermissionError>()(
"GitHubStackPermissionError",
stackErrorIdentity,
) {
override get message(): string {
return "You cannot update every branch in this stack. Check write access and fork maintainer permissions before retrying.";
}
}
export class GitHubStackRebaseFailedError extends Schema.TaggedError<GitHubStackRebaseFailedError>()(
"GitHubStackRebaseFailedError",
{ ...stackErrorIdentity, completed: Schema.Int, cause: Schema.Defect() },
) {
override get message(): string {
// A conflict or a refused push already says which layer and what to do about it.
return this.cause instanceof Error && this.cause.message !== ""
? this.cause.message
: `Stack rebase stopped at PR #${this.number} after ${this.completed} layers. Earlier updates remain on GitHub; resolve the failing layer before retrying.`;
}
}
export type GitHubStackActionError =
| GitHubStackChangedError
| GitHubStackUnsupportedError
| GitHubStackResponseInvalidError
| GitHubStackMergeRejectedError
| GitHubStackMergePendingError
| GitHubStackPermissionError
| GitHubStackRebaseFailedError;
const MergeResponse = Schema.Struct({
status: Schema.Literals(["pending", "merged", "enqueued", "failed"]),
details: Schema.Struct({
uuid: Schema.optional(Schema.String),
message: Schema.optional(Schema.String),
}),
});
const decodeBranchAccess = Schema.decodeEffect(
Schema.fromJsonString(
Schema.Struct({
data: Schema.Struct({
repository: Schema.NullOr(
Schema.Record(
Schema.String,
Schema.NullOr(
Schema.Struct({
headRepository: Schema.NullOr(
Schema.Struct({ viewerPermission: Schema.NullOr(Schema.String) }),
),
maintainerCanModify: Schema.Boolean,
}),
),
),
),
}),
}),
),
);
const decodeMergeResponse = Schema.decodeEffect(Schema.fromJsonString(MergeResponse));
/** Remote-only updates: a stack rebase works in a scratch clone, never the environment's checkout. */
export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* (input: {
cwd: string;
repository: string;
host: string;
number: number;
stackNumber: number;
expectedStackHeads?: ReadonlyArray<PullRequestStackHead>;
action: PullRequestAction;
mergeMethod?: PullRequestMergeMethod;
}) {
const api = yield* GitHubApi.GitHubApi;
const identity = {
repository: input.repository,
number: input.number,
stackNumber: input.stackNumber,
};
if (input.action !== "merge" && input.action !== "update-branch")
return yield* new GitHubStackUnsupportedError({ ...identity });
const endpoint = `repos/${input.repository}`;
const read = yield* api.rest({
host: input.host,
operation: "runGitHubStackAction",
path: `${endpoint}/stacks?pull_request=${input.number}`,
});
const decoded = decodePullRequestStacksJson(read.body);
if (Result.isFailure(decoded))
return yield* new GitHubStackResponseInvalidError({ ...identity, cause: decoded.failure });
const stack = decoded.success;
const targetIndex = stack?.layers.findIndex((layer) => layer.number === input.number) ?? -1;
const target = stack?.layers[targetIndex];
if (
stack?.number !== input.stackNumber ||
target === undefined ||
(input.action === "update-branch" && targetIndex !== stack.layers.length - 1)
) {
return yield* new GitHubStackChangedError({ ...identity, number: input.number, completed: 0 });
}
const affectedLayers =
input.action === "merge" ? stack.layers.slice(0, targetIndex + 1) : stack.layers;
const open = affectedLayers.filter((layer) => layer.state !== "merged");
if (input.action === "merge" && target.state !== "open")
return yield* new GitHubStackUnsupportedError({ ...identity });
if (
!input.expectedStackHeads ||
input.expectedStackHeads.length !== open.length ||
new Set(input.expectedStackHeads.map((layer) => layer.number)).size !== open.length ||
open.some(
(layer) =>
!layer.headSha ||
!input.expectedStackHeads?.some(
(expected) => expected.number === layer.number && expected.headSha === layer.headSha,
),
)
) {
return yield* new GitHubStackChangedError({ ...identity, number: input.number, completed: 0 });
}
if (open.length === 0 || open.some((layer) => layer.state !== "open"))
return yield* new GitHubStackUnsupportedError({ ...identity });
if (input.action === "update-branch") {
const [owner, name] = input.repository.split("/");
const permissions = yield* api.graphql({
host: input.host,
operation: "runGitHubStackAction",
allowReserve: true,
// `open` is non-empty here, so there is always a document.
...aliasedGraphQlDocument({
operation: "query",
alias: "pr",
key: (layer) => layer.number,
items: open,
shared: { owner: ["String!", owner], name: ["String!", name] },
variables: (layer) => ({ number: ["Int!", layer.number] }),
field: ({ number }) =>
`pullRequest(number: ${number}) { headRepository { viewerPermission } maintainerCanModify }`,
within: (fields) => `repository(owner: $owner, name: $name) {\n${fields}\n}`,
})!,
});
const access = yield* decodeBranchAccess(permissions).pipe(
Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })),
);
// viewerCanUpdateBranch is false for an already-current layer, even if rebasing its parent
// will make it stale. Check branch write access separately before touching any layer.
if (
open.some((layer) => {
const pr = access.data.repository?.[`pr${layer.number}`];
return (
!pr?.headRepository ||
(!pr.maintainerCanModify &&
!["ADMIN", "MAINTAIN", "WRITE"].includes(pr.headRepository.viewerPermission ?? ""))
);
})
)
return yield* new GitHubStackPermissionError({ ...identity });
// GitHub's own "Rebase stack" has no API, and its per-PR "update branch" replays the old
// copy of every lower layer into the one above it. The cascade moves each layer's own commits.
yield* cascadeRebaseStack({
host: input.host,
repository: input.repository,
base: stack.base,
layers: open.map((layer) => ({
number: layer.number,
headBranch: layer.headBranch,
headSha: layer.headSha!,
})),
}).pipe(
Effect.mapError((cause) =>
cause._tag === "GitHubStackRebaseConflictError" ||
cause._tag === "GitHubStackRebaseGitError"
? new GitHubStackRebaseFailedError({
...identity,
number: cause.number,
completed: cause.completed,
cause,
})
: cause,
),
);
return;
}
if (open.some((layer) => layer.isDraft))
return yield* new GitHubStackUnsupportedError({ ...identity });
const decode = (raw: string) =>
decodeMergeResponse(raw).pipe(
Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })),
);
const request = yield* api.rest({
host: input.host,
operation: "runGitHubStackAction",
method: "PUT",
path: `${endpoint}/pulls/${input.number}/merge-async`,
body: {
merge_method: input.mergeMethod ?? "merge",
merge_action: "default",
sha: target.headSha,
},
});
let result = yield* decode(request.body);
const deadline = (yield* Clock.currentTimeMillis) + 5 * 60_000;
for (
let attempt = 0;
result.status === "pending" && (yield* Clock.currentTimeMillis) < deadline;
attempt++
) {
const uuid = result.details.uuid;
if (!uuid) return yield* new GitHubStackResponseInvalidError({ ...identity });
yield* Effect.sleep(Math.min(1_000 * 2 ** attempt, 10_000));
const poll = yield* api.rest({
host: input.host,
operation: "runGitHubStackAction",
path: `${endpoint}/pulls/${input.number}/merge-async/${encodeURIComponent(uuid)}`,
});
result = yield* decode(poll.body);
}
if (result.status === "pending") return yield* new GitHubStackMergePendingError({ ...identity });
if (result.status === "failed")
return yield* new GitHubStackMergeRejectedError({ ...identity, cause: result });
});
@@ -0,0 +1,155 @@
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Base64 from "effect/encoding/Base64";
import * as GitHubApi from "./GitHubApi.ts";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
/** One open layer of a stack, bottom to top, with the head the reader reviewed. */
export interface CascadeLayer {
readonly number: number;
readonly headBranch: string;
readonly headSha: string;
}
/** A layer's rebase hit a conflict; the layers below it are already rebased on GitHub. */
export class GitHubStackRebaseConflictError extends Schema.TaggedError<GitHubStackRebaseConflictError>()(
"GitHubStackRebaseConflictError",
{ number: Schema.Int, completed: Schema.Int },
) {
override get message(): string {
return `PR #${this.number} conflicts with the layer below it. ${this.completed} layers were rebased; resolve #${this.number} with \`gh stack rebase\` and push.`;
}
}
/** Git failed for a reason other than a conflict: the fetch, or a push GitHub refused. */
export class GitHubStackRebaseGitError extends Schema.TaggedError<GitHubStackRebaseGitError>()(
"GitHubStackRebaseGitError",
{ step: Schema.String, number: Schema.Int, completed: Schema.Int, cause: Schema.Defect() },
) {
override get message(): string {
return `Stack rebase stopped at PR #${this.number} while ${this.step}. ${this.completed} layers were rebased.`;
}
}
/** The git URL of a repository on a GitHub host, which is also where its token is good. */
function remoteUrl(host: string, repository: string): string {
return `https://${host.trim().toLowerCase()}/${repository}.git`;
}
/**
* GitHub's own "Rebase stack": every open layer, bottom to top, onto the new head of the layer
* below it (the bottom one onto the stack's base). Each layer moves only its own commits —
* `git rebase --onto <new parent> <old parent>` — so a rebased lower layer is never replayed into
* the one above it, which is what GitHub's per-PR "update branch" does and why it conflicts.
*
* It works in a throwaway clone, so the environment's checkout never moves, and pushes each
* layer with a lease on the head that was reviewed, so a push that landed meanwhile is refused
* rather than overwritten. The stacks API has no rebase endpoint to call instead.
*/
export const cascadeRebaseStack = Effect.fn("cascadeRebaseStack")(function* (input: {
readonly host: string;
readonly repository: string;
readonly base: string;
readonly layers: ReadonlyArray<CascadeLayer>;
/** Where to fetch and push; the repository's own URL on its host unless a test points elsewhere. */
readonly remote?: string;
}) {
const api = yield* GitHubApi.GitHubApi;
const { process } = yield* SourceControlHost.SourceControlHost;
const fileSystem = yield* FileSystem.FileSystem;
const { token } = yield* api.credential(input.host);
const first = input.layers[0];
if (first === undefined) return 0;
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-stack-rebase-" }).pipe(
Effect.mapError(
(cause) =>
new GitHubStackRebaseGitError({
step: "preparing",
number: first.number,
completed: 0,
cause,
}),
),
);
// The token rides in a header for this process only: never in the URL, argv, or git config.
const remote = input.remote ?? remoteUrl(input.host, input.repository);
const authorization = `AUTHORIZATION: basic ${Base64.encode(`x-access-token:${Redacted.value(token)}`)}`;
const env = {
GIT_TERMINAL_PROMPT: "0",
GIT_CONFIG_COUNT: "3",
GIT_CONFIG_KEY_0: `http.${remote}.extraheader`,
GIT_CONFIG_VALUE_0: authorization,
GIT_CONFIG_KEY_1: "user.name",
GIT_CONFIG_VALUE_1: "T3 Code",
GIT_CONFIG_KEY_2: "user.email",
GIT_CONFIG_VALUE_2: "[email protected]",
};
const git = (args: ReadonlyArray<string>, allowNonZeroExit = false) =>
process.run({
operation: "cascadeRebaseStack",
command: "git",
args,
cwd: directory,
env,
timeoutMs: 120_000,
...(allowNonZeroExit ? { allowNonZeroExit: true } : {}),
});
const failed = (step: string, number: number, completed: number) => (cause: unknown) =>
new GitHubStackRebaseGitError({ step, number, completed, cause });
yield* git(["init", "--quiet"]).pipe(Effect.mapError(failed("preparing", first.number, 0)));
yield* git(["remote", "add", "origin", remote]).pipe(
Effect.mapError(failed("preparing", first.number, 0)),
);
yield* git([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+refs/heads/${input.base}:refs/remotes/origin/${input.base}`,
...input.layers.map(
(layer) => `+refs/heads/${layer.headBranch}:refs/remotes/origin/${layer.headBranch}`,
),
]).pipe(Effect.mapError(failed("fetching", first.number, 0)));
let parentOld = `origin/${input.base}`;
let parentNew = `origin/${input.base}`;
for (const [index, layer] of input.layers.entries()) {
// The bottom layer's old parent is where it forked from the base; above that it is the
// reviewed head of the layer below, which is exactly the commits this layer must not replay.
const upstream =
index === 0
? (yield* git(["merge-base", parentOld, layer.headSha]).pipe(
Effect.mapError(failed("reading the fork point", layer.number, index)),
)).stdout.trim()
: parentOld;
yield* git(["checkout", "--quiet", "--detach", layer.headSha]).pipe(
Effect.mapError(failed("checking out", layer.number, index)),
);
const rebase = yield* git(["rebase", "--quiet", "--onto", parentNew, upstream], true).pipe(
Effect.mapError(failed("rebasing", layer.number, index)),
);
if (rebase.exitCode !== 0) {
yield* git(["rebase", "--abort"], true).pipe(Effect.ignore);
return yield* new GitHubStackRebaseConflictError({ number: layer.number, completed: index });
}
const rebased = (yield* git(["rev-parse", "HEAD"]).pipe(
Effect.mapError(failed("rebasing", layer.number, index)),
)).stdout.trim();
if (rebased !== layer.headSha) {
yield* git([
"push",
"--quiet",
`--force-with-lease=refs/heads/${layer.headBranch}:${layer.headSha}`,
"origin",
`${rebased}:refs/heads/${layer.headBranch}`,
]).pipe(Effect.mapError(failed("pushing", layer.number, index)));
}
parentOld = layer.headSha;
parentNew = rebased;
}
return input.layers.length;
}, Effect.scoped);