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

@@ -1,525 +0,0 @@
import { describe, expect, it } from "@effect/vitest";
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 * as VcsProcess from "../vcs/VcsProcess.ts";
import * as ServerSettings from "../serverSettings.ts";
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: VcsProcess.VcsProcess["Service"]["run"]) =>
GitHubCredentials.layer.pipe(
Layer.provide(Layer.mock(VcsProcess.VcsProcess)({ run })),
Layer.provide(NodeServices.layer),
Layer.provide(ServerSettings.layerTest()),
);
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,
}),
),
),
),
);
});
-598
View File
@@ -1,598 +0,0 @@
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>("t3/sourceControl/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>(
"t3/sourceControl/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
>;
}
>()("t3/sourceControl/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),
);
@@ -1,170 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";
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 { ChildProcessSpawner } from "effect/process";
import * as ServerSettings from "../serverSettings.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCredentials from "./GitHubCredentials.ts";
const TOKEN_VARIABLES = [
"GH_TOKEN",
"GITHUB_TOKEN",
"GH_ENTERPRISE_TOKEN",
"GITHUB_ENTERPRISE_TOKEN",
] as const;
function harness(
hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }> = {},
signedOut: ReadonlyArray<string> = [],
tokens: Record<string, string> = {},
) {
const calls: Array<ReadonlyArray<string>> = [];
const process = Layer.mock(VcsProcess.VcsProcess)({
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(
ServerSettings.ServerSettingsService.layerTest({ github: { hosts, tokens } }),
),
Layer.provide(process),
Layer.provide(NodeServices.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* ServerSettings.ServerSettingsService;
expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");
yield* settings.updateSettings({
github: { hosts: { "github.com": { account: "work", enabled: true } } },
});
expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("token-for-work");
yield* settings.updateSettings({ github: { hosts: { "github.com": { enabled: false } } } });
expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(
"GitHubHostDisabledError",
);
yield* settings.updateSettings({ 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));
});
});
@@ -1,262 +0,0 @@
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 ServerSettings from "../serverSettings.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
/** 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>;
}
>()("t3/sourceControl/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 process = yield* VcsProcess.VcsProcess;
const serverSettings = yield* ServerSettings.ServerSettingsService;
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) =>
serverSettings.getSettings.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) =>
serverSettings.getSettings.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
@@ -24,6 +24,8 @@ export const layer = Layer.effect(
settings: { get: serverSettings.getSettings },
process: { run: process.run },
git: {
execute: git.execute,
resolveCommit: git.resolveCommit,
remotes: (cwd) =>
vcsRegistry.resolve({ cwd }).pipe(Effect.map((handle) => handle.driver.listRemotes(cwd))),
readConfigValue: git.readConfigValue,
@@ -20,7 +20,8 @@ import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/Azu
import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli";
import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
import * as GitHubApi from "./GitHubApi.ts";
import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
@@ -46,6 +47,7 @@ const layerSourceControlProviderRegistryTest = (input: {
Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),
Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
ServerSettings.ServerSettingsService.layerTest(),
Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
Layer.mock(GitHubApi.GitHubApi)({}),
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
Layer.mock(GitLabCli.GitLabCli)({}),
@@ -18,8 +18,9 @@ import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops
import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as GitHubApi from "./GitHubApi.ts";
import * as GitHubCredentials from "./GitHubCredentials.ts";
import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials";
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
@@ -115,6 +116,7 @@ function makeRegistry(input: {
Layer.mock(BitbucketApi.BitbucketApi)({}),
Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
ServerSettings.ServerSettingsService.layerTest(),
Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}),
Layer.mock(GitHubApi.GitHubApi)({
// No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
@@ -11,7 +11,6 @@ import {
import type { SourceControlProviderKind } from "@t3tools/contracts";
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
import * as BuiltInDrivers from "./builtInDrivers.ts";
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
import {
@@ -302,8 +301,6 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
);
export const make = Effect.gen(function* () {
const github = yield* GitHubSourceControlProvider.make;
const githubDiscovery = yield* GitHubSourceControlProvider.makeDiscovery;
const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) =>
driver.make.pipe(
Effect.map((instance): SourceControlProviderRegistration => ({
@@ -313,19 +310,7 @@ export const make = Effect.gen(function* () {
})),
),
);
// Discovery lists hosts in this order, so it is kept while hosts move into packages.
const order = ["github", "gitlab", "azure-devops", "bitbucket", "forgejo"];
const registrations: ReadonlyArray<SourceControlProviderRegistration> = [
{
kind: "github",
provider: github,
discovery: githubDiscovery,
},
...drivers,
];
return yield* makeWithProviders(
registrations.toSorted((left, right) => order.indexOf(left.kind) - order.indexOf(right.kind)),
);
return yield* makeWithProviders(drivers);
});
export const layer = Layer.effect(SourceControlProviderRegistry, make);
@@ -15,6 +15,9 @@ import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/serv
import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver";
import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli";
import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver";
import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
import * as GitHubDriver from "@t3tools/source-control-github/server/driver";
import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli";
import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli";
import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver";
@@ -24,6 +27,7 @@ import * as Layer from "effect/Layer";
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
const drivers = [
GitHubDriver.driver,
GitLabDriver.driver,
AzureDevOpsDriver.driver,
BitbucketDriver.driver,
@@ -34,12 +38,16 @@ const drivers = [
export type BuiltInSourceControlDriversEnv =
(typeof drivers)[number] extends SourceControlDriver<infer R> ? R : never;
/** Ordered as the hosts appear in discovery. */
export const BUILT_IN_SOURCE_CONTROL_DRIVERS: ReadonlyArray<
SourceControlDriver<BuiltInSourceControlDriversEnv>
> = drivers;
/** The services the built-in drivers' packages own, plus the host port they all run against. */
export const layer = Layer.mergeAll(
// `GitHubApi.layerWithDependencies` carries the quota reserve and rate-limit pause every GitHub
// reader shares, so the server builds it once, here.
GitHubPullRequestApi.layer.pipe(Layer.provideMerge(GitHubApi.layerWithDependencies)),
AzureDevOpsPullRequestCli.layer.pipe(Layer.provideMerge(AzureDevOpsCli.layer)),
BitbucketPullRequestApi.layer.pipe(Layer.provideMerge(BitbucketApi.layer)),
ForgejoCli.layer,
@@ -1,103 +0,0 @@
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)
);
}
@@ -1,145 +0,0 @@
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);
}
@@ -1,87 +0,0 @@
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);
});
});
@@ -1,192 +0,0 @@
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;
}
@@ -1,105 +0,0 @@
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);
}),
);
});
@@ -1,100 +0,0 @@
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;
}
});
@@ -1,86 +0,0 @@
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)),
);
});
@@ -1,122 +0,0 @@
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>;
}
>()("t3/sourceControl/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);
@@ -0,0 +1,173 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi";
import { cascadeRebaseStack } from "@t3tools/source-control-github/server/githubStackRebase";
import * as ServerSettings from "../serverSettings.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
const layer = Layer.mergeAll(
Layer.mock(GitHubApi.GitHubApi)({
credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
}),
// The cascade runs real git through the server's host; the git driver itself is never asked.
ServerSourceControlHost.layer.pipe(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
Layer.provide(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})),
Layer.provideMerge(VcsProcess.layer),
),
).pipe(Layer.provideMerge(NodeServices.layer));
/**
* A bare "GitHub" holding the live-run stack: `main` moved ahead after the stack was cut, and a
* second layer sits on the first. Returns each branch's head.
*/
const setup = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const process = yield* VcsProcess.VcsProcess;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cascade-test-" });
const remote = `${root}/remote.git`;
const work = `${root}/work`;
const git = (cwd: string, ...args: string[]) =>
process
.run({
operation: "test",
command: "git",
args,
cwd,
env: {
GIT_AUTHOR_NAME: "t",
GIT_AUTHOR_EMAIL: "t@t",
GIT_COMMITTER_NAME: "t",
GIT_COMMITTER_EMAIL: "t@t",
},
})
.pipe(Effect.map((out) => out.stdout.trim()));
const write = (path: string, text: string) => fs.writeFileString(`${work}/${path}`, text);
yield* git(root, "init", "--quiet", "--bare", "-b", "main", remote);
yield* git(root, "clone", "--quiet", remote, work);
yield* write("index.ts", "export const answer = 41;\n");
yield* git(work, "add", "-A");
yield* git(work, "commit", "--quiet", "-m", "Initial");
yield* git(work, "switch", "--quiet", "-c", "feat/answer-42");
yield* write("index.ts", "export const answer = 42;\n");
yield* git(work, "commit", "--quiet", "-am", "A: set the answer to 42");
yield* git(work, "switch", "--quiet", "-c", "feat/answer-doc");
yield* write("index.ts", "/** The answer. */\nexport const answer = 42;\n");
yield* git(work, "commit", "--quiet", "-am", "B: document the answer");
yield* git(work, "switch", "--quiet", "main");
yield* write("README.md", "main moved ahead\n");
yield* git(work, "add", "-A");
yield* git(work, "commit", "--quiet", "-m", "Docs");
yield* git(work, "push", "--quiet", "origin", "main", "feat/answer-42", "feat/answer-doc");
const head = (branch: string) => git(remote, "rev-parse", `refs/heads/${branch}`);
return {
remote,
head,
git: (...args: string[]) => git(remote, ...args),
layers: [
{ number: 1, headBranch: "feat/answer-42", headSha: yield* head("feat/answer-42") },
{ number: 2, headBranch: "feat/answer-doc", headSha: yield* head("feat/answer-doc") },
],
};
});
it.layer(layer)("cascadeRebaseStack", (it) => {
it.effect("moves each layer's own commits onto the rebased layer below it", () =>
Effect.gen(function* () {
const repo = yield* setup;
const completed = yield* cascadeRebaseStack({
host: "github.com",
repository: "acme/web",
base: "main",
layers: repo.layers,
remote: repo.remote,
});
assert.strictEqual(completed, 2);
const main = yield* repo.head("main");
const bottom = yield* repo.head("feat/answer-42");
const top = yield* repo.head("feat/answer-doc");
// Bottom sits on the new main; top sits on the new bottom with only its own commit.
expect(yield* repo.git("rev-parse", `${bottom}~1`)).toBe(main);
expect(yield* repo.git("rev-parse", `${top}~1`)).toBe(bottom);
expect(yield* repo.git("log", "--format=%s", `${bottom}..${top}`)).toBe(
"B: document the answer",
);
}).pipe(Effect.scoped),
);
it.effect("refuses to overwrite a layer pushed after it was reviewed", () =>
Effect.gen(function* () {
const repo = yield* setup;
const stale = [
repo.layers[0]!,
// Reviewed at the bottom layer's head, but the branch is really at its own commit.
{ ...repo.layers[1]!, headSha: repo.layers[0]!.headSha },
];
const error = yield* Effect.flip(
cascadeRebaseStack({
host: "github.com",
repository: "acme/web",
base: "main",
layers: stale,
remote: repo.remote,
}),
);
expect(error).toMatchObject({ _tag: "GitHubStackRebaseGitError", number: 2, completed: 1 });
expect(yield* repo.head("feat/answer-doc")).toBe(repo.layers[1]!.headSha);
}).pipe(Effect.scoped),
);
it.effect("stops at a conflicting layer and leaves it untouched", () =>
Effect.gen(function* () {
const repo = yield* setup;
// Make main conflict with the bottom layer's change to the same line.
const fs = yield* FileSystem.FileSystem;
const process = yield* VcsProcess.VcsProcess;
const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cascade-conflict-" });
const run = (...args: string[]) =>
process.run({
operation: "test",
command: "git",
args,
cwd: scratch,
env: {
GIT_AUTHOR_NAME: "t",
GIT_AUTHOR_EMAIL: "t@t",
GIT_COMMITTER_NAME: "t",
GIT_COMMITTER_EMAIL: "t@t",
},
});
yield* run("clone", "--quiet", repo.remote, ".");
yield* fs.writeFileString(`${scratch}/index.ts`, "export const answer = 43;\n");
yield* run("commit", "--quiet", "-am", "Conflict");
yield* run("push", "--quiet", "origin", "main");
const error = yield* Effect.flip(
cascadeRebaseStack({
host: "github.com",
repository: "acme/web",
base: "main",
layers: repo.layers,
remote: repo.remote,
}),
);
expect(error).toMatchObject({
_tag: "GitHubStackRebaseConflictError",
number: 1,
completed: 0,
});
expect(yield* repo.head("feat/answer-42")).toBe(repo.layers[0]!.headSha);
}).pipe(Effect.scoped),
);
});