refactor(server): GitHub rate limits read the response headers #16986
Mergedjuliusmarmingemerged 3 commits into
t3code/github-fold-repository-api fromrefs/pull/16986/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge added labelsmacroscope-review
- apps/server/src/sourceControl/GitHubApi.ts lines 402 to 406Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -403,7 +393,12 @@403393 });404394 const { token, fingerprint } = yield* credential(host);405395 const scope = yield* SourceControlRateLimit.CredentialScope;406- const key = { provider: "github" as const, host };396+ // REST spends `core` and GraphQL its own quota; GitHub resets and pauses them separately.397+ const resource = input.graphql === true ? "graphql" : "core";398+ const key = { provider: "github" as const, host, resource };407399 const run = Effect.gen(function* () {408- const lease = yield* limits409- .check(key, input.allowReserve ? { allowPaused: true } : undefined)400+ const lease = yield* quota401+ .admit(host, resource, { allowReserve: input.allowReserve })402+ .pipe(403+ Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),404+ )apps/server/src/sourceControl/GitHubApi.ts line 398OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -403,4 +393,6 @@403393 });404394 const { token, fingerprint } = yield* credential(host);405395 const scope = yield* SourceControlRateLimit.CredentialScope;406- const key = { provider: "github" as const, host };396+ // REST spends `core` and GraphQL its own quota; GitHub resets and pauses them separately.397+ const resource = input.graphql === true ? "graphql" : "core";398+ const key = { provider: "github" as const, host, resource };apps/server/src/sourceControl/githubQuota.ts lines 84 to 84OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+ readonly observe: (65+ host: string,66+ headers: Readonly<Record<string, string | undefined>>,67+ ) => Effect.Effect<void>;68+ }69+>()("t3/sourceControl/githubQuota") {}70+71+const make = Effect.gen(function* () {72+ const snapshots = yield* Ref.make<ReadonlyMap<string, QuotaSnapshot>>(new Map());73+ const keyOf = (host: string, resource: string, scope: string) =>74+ `${host.trim().toLowerCase()}\0${resource}\0${scope}`;75+76+ const admit: GitHubQuota["Service"]["admit"] = Effect.fn("GitHubQuota.admit")(77+ function* (host, resource, options) {78+ const now = yield* Clock.currentTimeMillis;79+ const key = keyOf(host, resource, yield* SourceControlRateLimit.CredentialScope);80+ const retryAt = yield* Ref.modify(snapshots, (current) => {81+ const snapshot = current.get(key);82+ if (snapshot === undefined || snapshot.resetAtMs <= now) return [null, current] as const;83+ const remaining = snapshot.remaining - 1;84+ if (options?.allowReserve !== true && remaining < snapshot.limit * RESERVE_RATIO) {apps/server/src/sourceControl/githubQuota.ts line 113OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ provider: "github",94+ host: host.trim().toLowerCase(),95+ retryAt,96+ });97+ },98+ );99+100+ const observe: GitHubQuota["Service"]["observe"] = Effect.fn("GitHubQuota.observe")(101+ function* (host, headers) {102+ const quota = quotaFromHeaders(headers);103+ if (quota === null) return;104+ const key = keyOf(host, quota.resource, yield* SourceControlRateLimit.CredentialScope);105+ yield* Ref.update(snapshots, (current) => {106+ const previous = current.get(key);107+ // Within one window the quota only falls, so the lower balance wins: an answer that108+ // finished out of order, or one that predates requests admitted since, says too much is109+ // left. An answer from an older window must not replace the current one.110+ if (111+ previous !== undefined &&112+ (quota.resetAtMs < previous.resetAtMs ||113+ (quota.resetAtMs === previous.resetAtMs && quota.remaining > previous.remaining))
- apps/server/src/sourceControl/githubQuota.ts line 113OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ provider: "github",94+ host: host.trim().toLowerCase(),95+ retryAt,96+ });97+ },98+ );99+100+ const observe: GitHubQuota["Service"]["observe"] = Effect.fn("GitHubQuota.observe")(101+ function* (host, headers) {102+ const quota = quotaFromHeaders(headers);103+ if (quota === null) return;104+ const key = keyOf(host, quota.resource, yield* SourceControlRateLimit.CredentialScope);105+ yield* Ref.update(snapshots, (current) => {106+ const previous = current.get(key);107+ // Within one window the quota only falls, so the lower balance wins: an answer that108+ // finished out of order, or one that predates requests admitted since, says too much is109+ // left. An answer from an older window must not replace the current one.110+ if (111+ previous !== undefined &&112+ (quota.resetAtMs < previous.resetAtMs ||113+ (quota.resetAtMs === previous.resetAtMs && quota.remaining > previous.remaining))apps/server/src/sourceControl/SourceControlRateLimit.ts line 72OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -64,4 +69,4 @@6469 >()("t3/sourceControl/SourceControlRateLimit") {}65706671 function normalizedKey(key: RateLimitKey, scope: string): string {67- return `${key.provider}\0${key.host.trim().toLowerCase()}\0${scope}`;72+ return `${key.provider}\0${key.host.trim().toLowerCase()}\0${key.resource ?? ""}\0${scope}`;
juliusmarminge changed the title
- apps/server/src/sourceControl/GitHubApi.ts lines 402 to 406Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -403,7 +393,14 @@403393 });404394 const { token, fingerprint } = yield* credential(host);405395 const scope = yield* SourceControlRateLimit.CredentialScope;396+ // REST spends `core` and GraphQL its own quota, each with its own reserve. Every REST path397+ // this reads today is `core`; a `search/` read would need its own resource here. A refusal398+ // still pauses the whole host, the key PullRequestService records its own backoff under.399+ const resource = input.graphql === true ? "graphql" : "core";406400 const key = { provider: "github" as const, host };407401 const run = Effect.gen(function* () {408- const lease = yield* limits409- .check(key, input.allowReserve ? { allowPaused: true } : undefined)402+ const lease = yield* quota403+ .admit(host, resource, { allowReserve: input.allowReserve })404+ .pipe(405+ Effect.andThen(limits.check(key, input.allowReserve ? { allowPaused: true } : undefined)),406+ )apps/server/src/sourceControl/githubQuota.ts lines 84 to 87Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ ) => Effect.Effect<void, SourceControlRateLimit.SourceControlRateLimitPausedError>;68+ readonly observe: (69+ host: string,70+ headers: Readonly<Record<string, string | undefined>>,71+ ) => Effect.Effect<void>;72+ }73+>()("t3/sourceControl/githubQuota") {}74+75+const make = Effect.gen(function* () {76+ const snapshots = yield* Ref.make<ReadonlyMap<string, QuotaSnapshot>>(new Map());77+ const keyOf = (host: string, resource: string, scope: string) =>78+ `${host.trim().toLowerCase()}\0${resource}\0${scope}`;79+80+ const admit: GitHubQuota["Service"]["admit"] = Effect.fn("GitHubQuota.admit")(81+ function* (host, resource, options) {82+ const now = yield* Clock.currentTimeMillis;83+ const key = keyOf(host, resource, yield* SourceControlRateLimit.CredentialScope);84+ const snapshot = (yield* Ref.get(snapshots)).get(key);85+ if (snapshot === undefined || snapshot.resetAtMs <= now) return;86+ const floor = options?.allowReserve === true ? 1 : snapshot.limit * RESERVE_RATIO;87+ if (snapshot.remaining >= floor) return;apps/server/src/sourceControl/githubQuota.ts lines 105 to 109OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +89,21 @@89+ provider: "github",90+ host: host.trim().toLowerCase(),91+ retryAt: snapshot.resetAtMs,92+ });93+ },94+ );95+96+ const observe: GitHubQuota["Service"]["observe"] = Effect.fn("GitHubQuota.observe")(97+ function* (host, headers) {98+ const quota = quotaFromHeaders(headers);99+ if (quota === null) return;100+ const key = keyOf(host, quota.resource, yield* SourceControlRateLimit.CredentialScope);101+ yield* Ref.update(snapshots, (current) => {102+ const previous = current.get(key);103+ // Within one window GitHub's count only falls, so an answer that finished out of order104+ // and reports more left is stale. An answer from an older window says nothing of this one.105+ if (106+ previous !== undefined &&107+ (quota.resetAtMs < previous.resetAtMs ||108+ (quota.resetAtMs === previous.resetAtMs && quota.remaining > previous.remaining))109+ ) {
juliusmarminge merged thisd720210
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
b8f42ae· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.