fix: reduce GitHub quota use with sharing enabled (#11888)
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
1 parent
b84f63bb13
commit
f4600d77dd
20 files changed
+1020
-273
No files matched your search
@@ -1,5 +1,8 @@
|
||||
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
@@ -10,6 +13,8 @@ import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
|
||||
import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
|
||||
|
||||
const encodeGitHubCliError = Schema.encodeEffect(Schema.fromJsonString(GitHubCli.GitHubCliError));
|
||||
|
||||
@@ -21,12 +26,18 @@ const processOutput = (stdout: string): VcsProcess.VcsProcessOutput => ({
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
const quotaOutput = (remaining = 5000, resetAt = "2099-01-01T00:00:00Z") =>
|
||||
processOutput(
|
||||
JSON.stringify({ data: { rateLimit: { cost: 1, limit: 5000, remaining, resetAt } } }),
|
||||
);
|
||||
|
||||
const mockRun = vi.fn<VcsProcess.VcsProcess["Service"]["run"]>();
|
||||
|
||||
const layer = GitHubCli.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsProcess.VcsProcess)({
|
||||
run: mockRun,
|
||||
run: (input) =>
|
||||
input.args[1] === "rate_limit" ? Effect.succeed(quotaOutput()) : mockRun(input),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -35,7 +46,98 @@ afterEach(() => {
|
||||
mockRun.mockReset();
|
||||
});
|
||||
|
||||
it.effect("shares quota checks, preserves the reserve, and resumes after reset", () =>
|
||||
Effect.gen(function* () {
|
||||
let probes = 0;
|
||||
const commands: string[] = [];
|
||||
let remaining = 501;
|
||||
let resetAt = DateTime.formatIso(
|
||||
DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 60_000),
|
||||
);
|
||||
const gh = yield* GitHubCli.make.pipe(
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.args[1] === "rate_limit") {
|
||||
probes++;
|
||||
assert.strictEqual(input.args[3], "enterprise.test");
|
||||
return quotaOutput(remaining, resetAt);
|
||||
}
|
||||
commands.push(input.args.slice(0, 2).join(" "));
|
||||
return processOutput("[]");
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const read = (command: string) =>
|
||||
gh.execute({
|
||||
cwd: "/repo",
|
||||
args:
|
||||
command === "repo"
|
||||
? ["repo", "view", "enterprise.test/acme/web", "--json", "name"]
|
||||
: ["pr", command, "--repo=enterprise.test/acme/web", "--json", "number"],
|
||||
});
|
||||
yield* read("list");
|
||||
const failure = yield* read("view").pipe(Effect.flip);
|
||||
assert.strictEqual(failure._tag, "GitHubCliRateLimitError");
|
||||
assert.strictEqual(probes, 1);
|
||||
assert.deepStrictEqual(commands, ["pr list"]);
|
||||
yield* read("view").pipe(Effect.provideService(GitHubCli.AllowGitHubReserve, true));
|
||||
yield* gh.execute({ cwd: "/repo", args: ["pr", "merge", "1"] });
|
||||
assert.deepStrictEqual(commands, ["pr list", "pr view", "pr merge"]);
|
||||
remaining = 0;
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
yield* read("repo").pipe(Effect.flip);
|
||||
assert.strictEqual(probes, 2);
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
remaining = 5000;
|
||||
resetAt = DateTime.formatIso(DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 60_000));
|
||||
yield* Effect.all([read("list"), read("repo")], { concurrency: 2 });
|
||||
assert.strictEqual(probes, 3);
|
||||
assert.deepStrictEqual(commands.slice(3).toSorted(), ["pr list", "repo view"]);
|
||||
}).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
|
||||
);
|
||||
|
||||
describe("GitHubCli.layer", () => {
|
||||
it.effect("shares the registry budget with CLI reads through nested layer providers", () =>
|
||||
Effect.gen(function* () {
|
||||
const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
|
||||
const gh = yield* GitHubCli.GitHubCli;
|
||||
yield* budget.observe("github.com", quotaOutput(0).stdout);
|
||||
const error = yield* gh.execute({ cwd: "/repo", args: ["pr", "list"] }).pipe(Effect.flip);
|
||||
assert.strictEqual(error._tag, "GitHubCliRateLimitError");
|
||||
expect(mockRun).not.toHaveBeenCalled();
|
||||
}).pipe(Effect.provide(layer.pipe(Layer.provide(GitHubGraphQlBudget.layer)))),
|
||||
);
|
||||
|
||||
it.effect("keeps quota snapshots separate for verified credentials on the same host", () =>
|
||||
Effect.gen(function* () {
|
||||
let reads = 0;
|
||||
const gh = yield* GitHubCli.make.pipe(
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.args[1] === "rate_limit")
|
||||
return quotaOutput(input.env?.GH_TOKEN === "empty" ? 0 : 5000);
|
||||
reads++;
|
||||
return processOutput("[]");
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const read = (token: string) =>
|
||||
gh.execute({ cwd: "/repo", args: ["pr", "list", "--repo", "github.com/acme/web"] }).pipe(
|
||||
Effect.provideService(GitHubCli.PinnedGitHubCredential, {
|
||||
host: "github.com",
|
||||
token: Redacted.make(token),
|
||||
credentialFingerprint: token,
|
||||
}),
|
||||
);
|
||||
yield* read("empty").pipe(Effect.flip);
|
||||
yield* read("healthy");
|
||||
yield* read("empty").pipe(Effect.flip);
|
||||
assert.strictEqual(reads, 1);
|
||||
}).pipe(Effect.provide(Layer.merge(GitHubGraphQlBudget.layer, SourceControlRateLimit.layer))),
|
||||
);
|
||||
|
||||
it.effect("pins concurrent cached commands to their own verified credentials", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockImplementation((input) =>
|
||||
@@ -523,6 +625,15 @@ describe("GitHubCli.layer", () => {
|
||||
assert.include(error.detail, "gh api rate_limit");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.notInclude(error.message, "user ID");
|
||||
const paused = yield* gh
|
||||
.execute({ cwd: "/other-repo", args: ["pr", "list"] })
|
||||
.pipe(Effect.flip);
|
||||
assert.strictEqual(paused._tag, "GitHubCliRateLimitError");
|
||||
expect(mockRun).toHaveBeenCalledTimes(1);
|
||||
yield* TestClock.adjust("30 seconds");
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("[]")));
|
||||
yield* gh.execute({ cwd: "/other-repo", args: ["pr", "list"] });
|
||||
expect(mockRun).toHaveBeenCalledTimes(2);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,3 +1,6 @@
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -15,6 +18,8 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
|
||||
import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
@@ -30,7 +35,12 @@ export const PinnedGitHubCredential = Context.Reference<{
|
||||
readonly credentialFingerprint: string;
|
||||
} | null>("t3/sourceControl/PinnedGitHubCredential", { defaultValue: () => null });
|
||||
|
||||
function targetsVerifiedHost(args: ReadonlyArray<string>, host: string): boolean {
|
||||
export const AllowGitHubReserve = Context.Reference<boolean>(
|
||||
"t3/sourceControl/AllowGitHubReserve",
|
||||
{ defaultValue: () => false },
|
||||
);
|
||||
|
||||
function commandHosts(args: ReadonlyArray<string>): Array<string | null> {
|
||||
const hosts: Array<string | null> = [];
|
||||
const repositoryHost = (repository: string | undefined) => {
|
||||
if (repository === undefined) return null;
|
||||
@@ -54,6 +64,11 @@ function targetsVerifiedHost(args: ReadonlyArray<string>, host: string): boolean
|
||||
else if (arg.startsWith("-R")) hosts.push(repositoryHost(arg.slice(2)));
|
||||
else if (/^https?:\/\//i.test(arg)) hosts.push(repositoryHost(arg));
|
||||
}
|
||||
return hosts;
|
||||
}
|
||||
|
||||
function targetsVerifiedHost(args: ReadonlyArray<string>, host: string): boolean {
|
||||
const hosts = commandHosts(args);
|
||||
return hosts.length > 0 && hosts.every((target) => target === host);
|
||||
}
|
||||
|
||||
@@ -91,7 +106,7 @@ export class GitHubCliAuthenticationError extends Schema.TaggedError<GitHubCliAu
|
||||
|
||||
export class GitHubCliRateLimitError extends Schema.TaggedError<GitHubCliRateLimitError>()(
|
||||
"GitHubCliRateLimitError",
|
||||
gitHubCliFailureFields,
|
||||
{ ...gitHubCliFailureFields, retryAt: Schema.optionalKey(Schema.Finite) },
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub API rate limit exceeded. Run `gh api rate_limit` to inspect the quota and reset time.";
|
||||
@@ -274,17 +289,21 @@ export class GitHubCli extends Context.Service<
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly rateLimitHost?: string;
|
||||
readonly allowReserve?: boolean;
|
||||
}) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;
|
||||
|
||||
readonly listOpenPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headSelector: string;
|
||||
readonly limit?: number;
|
||||
readonly rateLimitHost?: string;
|
||||
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
|
||||
|
||||
readonly getPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly rateLimitHost?: string;
|
||||
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
|
||||
|
||||
readonly getRepositoryCloneUrls: (input: {
|
||||
@@ -308,6 +327,7 @@ export class GitHubCli extends Context.Service<
|
||||
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly rateLimitHost?: string;
|
||||
}) => Effect.Effect<string | null, GitHubCliError>;
|
||||
|
||||
readonly checkoutPullRequest: (input: {
|
||||
@@ -377,8 +397,10 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
|
||||
/** @public Service construction is part of the canonical Effect module API. */
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
|
||||
const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
|
||||
|
||||
const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
|
||||
const executeRaw: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.executeRaw")(
|
||||
function* (input) {
|
||||
const credential = yield* PinnedGitHubCredential;
|
||||
if (credential !== null && !targetsVerifiedHost(input.args, credential.host)) {
|
||||
@@ -416,11 +438,94 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
const quota = yield* Cache.makeWith(
|
||||
(key: string) => {
|
||||
const host = key.split("\0")[0]!;
|
||||
return executeRaw({
|
||||
cwd: globalThis.process.cwd(),
|
||||
args: [
|
||||
"api",
|
||||
"rate_limit",
|
||||
"--hostname",
|
||||
host,
|
||||
"--jq",
|
||||
".resources.graphql | {data:{rateLimit:{cost:1,limit:.limit,remaining:.remaining,resetAt:(.reset|todateiso8601)}}}",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.tap((result) => budget.observe(host, result.stdout)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
},
|
||||
{
|
||||
capacity: 32,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.seconds(30) : Duration.zero),
|
||||
},
|
||||
);
|
||||
const execute: GitHubCli["Service"]["execute"] = Effect.fn("GitHubCli.execute")(
|
||||
function* (input) {
|
||||
const [command, action] = input.args;
|
||||
if (
|
||||
!(
|
||||
(command === "pr" && (action === "list" || action === "view")) ||
|
||||
(command === "repo" && action === "view")
|
||||
)
|
||||
)
|
||||
return yield* executeRaw(input);
|
||||
const credential = yield* PinnedGitHubCredential;
|
||||
if (credential !== null && !targetsVerifiedHost(input.args, credential.host))
|
||||
return yield* executeRaw(input);
|
||||
const allowReserve = input.allowReserve ?? (yield* AllowGitHubReserve);
|
||||
const host = (
|
||||
credential?.host ??
|
||||
commandHosts(input.args).find((host) => host !== null) ??
|
||||
input.rateLimitHost ??
|
||||
input.env?.GH_HOST ??
|
||||
globalThis.process.env.GH_HOST ??
|
||||
"github.com"
|
||||
).toLowerCase();
|
||||
const key = { provider: "github" as const, host };
|
||||
const guarded = Effect.gen(function* () {
|
||||
const lease = yield* limits.check(key, allowReserve ? { allowPaused: true } : undefined);
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* Cache.get(quota, `${host}\0${credential?.credentialFingerprint ?? ""}`);
|
||||
yield* budget.query(host, "query {}", allowReserve ? { allowReserve: true } : undefined);
|
||||
return yield* executeRaw(input);
|
||||
}).pipe(
|
||||
Effect.tap(() => limits.recordSuccess({ ...key, lease })),
|
||||
Effect.tapError((error) =>
|
||||
error._tag === "GitHubCliRateLimitError"
|
||||
? limits.recordRateLimit({ ...key, lease })
|
||||
: Effect.void,
|
||||
),
|
||||
);
|
||||
});
|
||||
return yield* guarded.pipe(
|
||||
Effect.provideService(
|
||||
SourceControlRateLimit.CredentialScope,
|
||||
credential?.credentialFingerprint ?? (yield* SourceControlRateLimit.CredentialScope),
|
||||
),
|
||||
Effect.catchTags({
|
||||
SourceControlRateLimitPausedError: (cause) =>
|
||||
Effect.fail(
|
||||
new GitHubCliRateLimitError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
retryAt: cause.retryAt,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
listOpenPullRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
|
||||
allowReserve: true,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
@@ -458,6 +563,8 @@ export const make = Effect.gen(function* () {
|
||||
getPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
|
||||
allowReserve: true,
|
||||
args: [
|
||||
"pr",
|
||||
"view",
|
||||
@@ -533,6 +640,7 @@ export const make = Effect.gen(function* () {
|
||||
getDefaultBranch: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),
|
||||
args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
|
||||
}).pipe(
|
||||
Effect.map((value) => {
|
||||
@@ -548,4 +656,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitHubCli, make);
|
||||
export const layer = Layer.effect(GitHubCli, make).pipe(
|
||||
Layer.provideMerge(GitHubGraphQlBudget.layer),
|
||||
Layer.provideMerge(SourceControlRateLimit.layer),
|
||||
);
|
||||
@@ -30,6 +30,33 @@ function makeProvider(github: Partial<GitHubCli.GitHubCli["Service"]>) {
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("uses the enterprise quota for a current-repository default branch read", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* GitHubSourceControlProvider.make.pipe(
|
||||
Effect.provide(GitHubCli.layer),
|
||||
Effect.provideService(VcsProcess.VcsProcess, {
|
||||
run: (input) =>
|
||||
Effect.sync(() => {
|
||||
if (input.args[1] !== "rate_limit") return processResult("main");
|
||||
assert.strictEqual(input.args[3], "enterprise.test");
|
||||
return processResult(
|
||||
'{"data":{"rateLimit":{"cost":1,"limit":5000,"remaining":5000,"resetAt":"2099-01-01T00:00:00Z"}}}',
|
||||
);
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const branch = yield* provider.getDefaultBranch({
|
||||
cwd: "/enterprise-repo",
|
||||
context: {
|
||||
provider: { kind: "github", name: "GitHub Enterprise", baseUrl: "https://enterprise.test" },
|
||||
remoteName: "origin",
|
||||
remoteUrl: "https://enterprise.test/acme/web.git",
|
||||
},
|
||||
});
|
||||
assert.strictEqual(branch, "main");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -127,6 +127,9 @@ export const make = Effect.gen(function* () {
|
||||
.listOpenPullRequests({
|
||||
cwd: input.cwd,
|
||||
headSelector: input.headSelector,
|
||||
...(input.context === undefined
|
||||
? {}
|
||||
: { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
|
||||
...(input.limit !== undefined ? { limit: input.limit } : {}),
|
||||
})
|
||||
.pipe(
|
||||
@@ -152,6 +155,9 @@ export const make = Effect.gen(function* () {
|
||||
return github
|
||||
.execute({
|
||||
cwd: input.cwd,
|
||||
...(input.context === undefined
|
||||
? {}
|
||||
: { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
@@ -267,23 +273,30 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
listChangeRequests,
|
||||
getChangeRequest: (input) =>
|
||||
github.getPullRequest(input).pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "getChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
github
|
||||
.getPullRequest({
|
||||
...input,
|
||||
...(input.context === undefined
|
||||
? {}
|
||||
: { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(toChangeRequest),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "getChangeRequest",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.reference,
|
||||
),
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
createChangeRequest: (input) =>
|
||||
github
|
||||
.createPullRequest({
|
||||
@@ -344,19 +357,26 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
getDefaultBranch: (input) =>
|
||||
github.getDefaultBranch(input).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "getDefaultBranch",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
github
|
||||
.getDefaultBranch({
|
||||
...input,
|
||||
...(input.context === undefined
|
||||
? {}
|
||||
: { rateLimitHost: new URL(input.context.provider.baseUrl).host }),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "getDefaultBranch",
|
||||
command: error.command,
|
||||
cwd: input.cwd,
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
checkoutChangeRequest: (input) =>
|
||||
github.checkoutPullRequest(input).pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -6,6 +6,22 @@ import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";
|
||||
|
||||
const github = { provider: "github" as const, host: "github.com" };
|
||||
|
||||
it.effect("isolates cooldowns for verified credentials on the same host", () =>
|
||||
Effect.gen(function* () {
|
||||
const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
|
||||
yield* limits
|
||||
.recordRateLimit({ ...github, lease: 0 })
|
||||
.pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, "first"));
|
||||
yield* limits
|
||||
.check(github)
|
||||
.pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, "second"));
|
||||
const error = yield* limits
|
||||
.check(github)
|
||||
.pipe(Effect.provideService(SourceControlRateLimit.CredentialScope, "first"), Effect.flip);
|
||||
assert.strictEqual(error._tag, "SourceControlRateLimitPausedError");
|
||||
}).pipe(Effect.provide(SourceControlRateLimit.layer)),
|
||||
);
|
||||
|
||||
it("parses Retry-After seconds and HTTP dates", () => {
|
||||
assert.equal(SourceControlRateLimit.retryAtFromHeader("120", 1_000), 121_000);
|
||||
assert.equal(
|
||||
|
||||
@@ -13,6 +13,10 @@ import {
|
||||
const FALLBACK_COOLDOWN = Duration.seconds(30);
|
||||
const MAX_FALLBACK_COOLDOWN = Duration.minutes(15);
|
||||
|
||||
export const CredentialScope = Context.Reference<string>("t3/sourceControl/CredentialScope", {
|
||||
defaultValue: () => "",
|
||||
});
|
||||
|
||||
interface RateLimitKey {
|
||||
readonly provider: SourceControlProviderKind;
|
||||
readonly host: string;
|
||||
@@ -59,8 +63,8 @@ export class SourceControlRateLimit extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/SourceControlRateLimit") {}
|
||||
|
||||
function normalizedKey(key: RateLimitKey): string {
|
||||
return `${key.provider}\0${key.host.trim().toLowerCase()}`;
|
||||
function normalizedKey(key: RateLimitKey, scope: string): string {
|
||||
return `${key.provider}\0${key.host.trim().toLowerCase()}\0${scope}`;
|
||||
}
|
||||
|
||||
function fallbackCooldownMs(attempt: number): number {
|
||||
@@ -90,7 +94,8 @@ export const make = Effect.gen(function* () {
|
||||
"SourceControlRateLimit.check",
|
||||
)(function* (input, options) {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const entry = (yield* Ref.get(entries)).get(normalizedKey(input));
|
||||
const key = normalizedKey(input, yield* CredentialScope);
|
||||
const entry = (yield* Ref.get(entries)).get(key);
|
||||
if (entry !== undefined && entry.retryAt > now && options?.allowPaused !== true) {
|
||||
return yield* new SourceControlRateLimitPausedError({
|
||||
provider: input.provider,
|
||||
@@ -105,8 +110,8 @@ export const make = Effect.gen(function* () {
|
||||
"SourceControlRateLimit.recordRateLimit",
|
||||
)(function* (input) {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const key = normalizedKey(input, yield* CredentialScope);
|
||||
yield* Ref.update(entries, (current) => {
|
||||
const key = normalizedKey(input);
|
||||
const previous = current.get(key);
|
||||
if (previous !== undefined && previous.generation > input.lease) {
|
||||
if (previous.retryAt <= now && (input.retryAt === undefined || input.retryAt <= now)) {
|
||||
@@ -145,8 +150,8 @@ export const make = Effect.gen(function* () {
|
||||
"SourceControlRateLimit.recordSuccess",
|
||||
)(function* (input) {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const key = normalizedKey(input, yield* CredentialScope);
|
||||
yield* Ref.update(entries, (current) => {
|
||||
const key = normalizedKey(input);
|
||||
const previous = current.get(key);
|
||||
if (previous === undefined || previous.generation !== input.lease || previous.retryAt > now) {
|
||||
return current;
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";
|
||||
import { CredentialScope } from "./SourceControlRateLimit.ts";
|
||||
|
||||
const RESET_AT = "2026-08-13T14:00:00.000Z";
|
||||
const NEXT_RESET_AT = "2026-08-13T15:00:00.000Z";
|
||||
@@ -71,6 +72,23 @@ describe("GitHub GraphQL budget", () => {
|
||||
}).pipe(Effect.provide(GitHubGraphQlBudget.layer)),
|
||||
);
|
||||
|
||||
it.effect("isolates query reservations and observations by credential", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(BEFORE_RESET);
|
||||
const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
|
||||
const query = budget.query("github.com", "query { viewer { login } }");
|
||||
yield* budget
|
||||
.observe("github.com", rateLimit(0))
|
||||
.pipe(Effect.provideService(CredentialScope, "first"));
|
||||
yield* budget
|
||||
.observe("github.com", rateLimit(5000))
|
||||
.pipe(Effect.provideService(CredentialScope, "second"));
|
||||
yield* query.pipe(Effect.provideService(CredentialScope, "second"));
|
||||
const error = yield* query.pipe(Effect.provideService(CredentialScope, "first"), Effect.flip);
|
||||
expect(error.retryAt).toBe(Date.parse(RESET_AT));
|
||||
}).pipe(Effect.provide(GitHubGraphQlBudget.layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps the lower remaining value from out-of-order responses", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(BEFORE_RESET);
|
||||
@@ -181,6 +199,19 @@ describe("GitHub GraphQL budget", () => {
|
||||
}).pipe(Effect.provide(GitHubGraphQlBudget.layer)),
|
||||
);
|
||||
|
||||
it.effect("stops interactive reads when the reserve is exhausted", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(BEFORE_RESET);
|
||||
const budget = yield* GitHubGraphQlBudget.GitHubGraphQlBudget;
|
||||
yield* budget.observe("github.com", rateLimit(1, 5000, RESET_AT, 1));
|
||||
yield* budget.query("github.com", "query { viewer { login } }", { allowReserve: true });
|
||||
const error = yield* budget
|
||||
.query("github.com", "query { viewer { login } }", { allowReserve: true })
|
||||
.pipe(Effect.flip);
|
||||
expect(error.retryAt).toBe(Date.parse(RESET_AT));
|
||||
}).pipe(Effect.provide(GitHubGraphQlBudget.layer)),
|
||||
);
|
||||
|
||||
it.effect("ignores malformed or partial rate metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* TestClock.setTime(BEFORE_RESET);
|
||||
|
||||
@@ -85,8 +85,8 @@ export const make = Effect.gen(function* () {
|
||||
function* (host, document, options) {
|
||||
if (!isReadOperation(document)) return document;
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const key = `${hostKey(host)}\0${yield* SourceControlRateLimit.CredentialScope}`;
|
||||
const retryAt = yield* Ref.modify(snapshots, (current) => {
|
||||
const key = hostKey(host);
|
||||
const snapshot = current.get(key);
|
||||
if (snapshot === undefined) return [null, current] as const;
|
||||
if (snapshot.resetAtMs <= now) {
|
||||
@@ -94,8 +94,11 @@ export const make = Effect.gen(function* () {
|
||||
next.delete(key);
|
||||
return [null, next] as const;
|
||||
}
|
||||
const remaining = Math.max(0, snapshot.remaining - Math.max(1, snapshot.cost));
|
||||
if (options?.allowReserve !== true && remaining < snapshot.limit * GRAPHQL_RESERVE_RATIO) {
|
||||
const remaining = snapshot.remaining - Math.max(1, snapshot.cost);
|
||||
if (
|
||||
remaining < 0 ||
|
||||
(options?.allowReserve !== true && remaining < snapshot.limit * GRAPHQL_RESERVE_RATIO)
|
||||
) {
|
||||
return [snapshot.resetAtMs, current] as const;
|
||||
}
|
||||
const next = new Map(current);
|
||||
@@ -118,8 +121,8 @@ export const make = Effect.gen(function* () {
|
||||
)(function* (host, raw) {
|
||||
const snapshot = snapshotFrom(raw);
|
||||
if (snapshot === null) return;
|
||||
const key = `${hostKey(host)}\0${yield* SourceControlRateLimit.CredentialScope}`;
|
||||
yield* Ref.update(snapshots, (current) => {
|
||||
const key = hostKey(host);
|
||||
const previous = current.get(key);
|
||||
// Concurrent reads can finish out of order. Quota only falls within one reset window, and
|
||||
// an answer from an older window must not replace the current one.
|
||||
|
||||
Reference in new issue
Block a user