perf(source-control): stop gh rate-limit storms and idle git-status spawn churn (#7595)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -43,7 +43,8 @@ vi.mock('./gh-utils', async () => {
|
||||
|
||||
vi.mock('./rate-limit', () => ({
|
||||
rateLimitGuard: rateLimitGuardMock,
|
||||
noteRateLimitSpend: noteRateLimitSpendMock
|
||||
noteRateLimitSpend: noteRateLimitSpendMock,
|
||||
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' }))
|
||||
}))
|
||||
|
||||
import { countWorkItems, getWorkItem, listWorkItems, _resetOwnerRepoCache } from './client'
|
||||
|
||||
@@ -63,7 +63,8 @@ vi.mock('../git/runner', () => ({
|
||||
|
||||
vi.mock('./rate-limit', () => ({
|
||||
rateLimitGuard: rateLimitGuardMock,
|
||||
noteRateLimitSpend: noteRateLimitSpendMock
|
||||
noteRateLimitSpend: noteRateLimitSpendMock,
|
||||
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' }))
|
||||
}))
|
||||
|
||||
import {
|
||||
@@ -72,6 +73,7 @@ import {
|
||||
_resetMergeQueueCacheForTests,
|
||||
_resetOwnerRepoCache
|
||||
} from './client'
|
||||
import { _resetGhCwdRepoNegativeCache } from './gh-cwd-repo-negative-cache'
|
||||
import { GITHUB_WORK_ITEMS_QUERY_MAX_BYTES } from '../../shared/github-work-items-query-bounds'
|
||||
|
||||
describe('listWorkItems', () => {
|
||||
@@ -99,6 +101,25 @@ describe('listWorkItems', () => {
|
||||
getOwnerRepoForRemoteMock.mockResolvedValue(null)
|
||||
_resetOwnerRepoCache()
|
||||
_resetMergeQueueCacheForTests()
|
||||
_resetGhCwdRepoNegativeCache()
|
||||
})
|
||||
|
||||
it('stops re-spawning gh for a repo whose cwd resolution already failed with no remotes', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValue(null)
|
||||
getOwnerRepoMock.mockResolvedValue(null)
|
||||
ghExecFileAsyncMock.mockRejectedValue(
|
||||
Object.assign(new Error('Command failed: gh pr list\nno git remotes found'), {
|
||||
stderr: 'no git remotes found'
|
||||
})
|
||||
)
|
||||
|
||||
await expect(listWorkItems('/no-remote-repo', 36)).rejects.toThrow('no git remotes found')
|
||||
// The first refresh pays the two cwd-fallback spawns (issue + pr list).
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
|
||||
await expect(listWorkItems('/no-remote-repo', 36)).rejects.toThrow('no git remotes found')
|
||||
// The second refresh is served from the negative cache — zero new spawns.
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('runs both issue and PR GitHub searches for a mixed query and merges the results by recency', async () => {
|
||||
@@ -537,6 +558,22 @@ describe('listWorkItems', () => {
|
||||
expect(apiPath).not.toContain('-is:merged')
|
||||
})
|
||||
|
||||
it('returns zero without spawning gh when the search bucket is rate-limit blocked', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
rateLimitGuardMock.mockReturnValue({
|
||||
blocked: true,
|
||||
remaining: 0,
|
||||
limit: 30,
|
||||
resetAt: Math.floor(Date.now() / 1000) + 60
|
||||
} as unknown as { blocked: boolean })
|
||||
|
||||
await expect(countWorkItems('/repo-root', 'is:issue is:open')).resolves.toBe(0)
|
||||
|
||||
expect(rateLimitGuardMock).toHaveBeenCalledWith('search')
|
||||
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns zero for oversized count queries before resolving repo sources', async () => {
|
||||
const secret = 'main-github-work-items-secret'
|
||||
const oversizedQuery = secret + 'x'.repeat(GITHUB_WORK_ITEMS_QUERY_MAX_BYTES)
|
||||
|
||||
@@ -73,6 +73,12 @@ import {
|
||||
type HostedReviewExecutionOptions
|
||||
} from '../source-control/hosted-review-git-options'
|
||||
import { readLocalGitConfigSignature } from './local-git-config-signature'
|
||||
import {
|
||||
getRememberedGhCwdResolutionFailure,
|
||||
isGhCwdRepoResolutionFailure,
|
||||
rememberGhCwdResolutionFailure
|
||||
} from './gh-cwd-repo-negative-cache'
|
||||
import type { GitHubRepoContext } from './github-repository-identity'
|
||||
export { _resetOwnerRepoCache } from './gh-utils'
|
||||
export {
|
||||
getIssue,
|
||||
@@ -1005,6 +1011,32 @@ async function resolvePrWorkItemSource(
|
||||
return { source, originCandidate, upstreamCandidate }
|
||||
}
|
||||
|
||||
/**
|
||||
* gh exec for calls that rely on gh's own cwd→repo resolution (no explicit
|
||||
* owner/repo). Serves a remembered deterministic resolution failure without
|
||||
* spawning, so a remote-less repo costs one gh spawn per config change/TTL
|
||||
* instead of two per Tasks refresh.
|
||||
*/
|
||||
async function ghCwdResolvedExec(
|
||||
context: GitHubRepoContext,
|
||||
args: string[],
|
||||
ghOptions: GhExecOptions
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
const remembered = await getRememberedGhCwdResolutionFailure(context)
|
||||
if (remembered !== null) {
|
||||
throw new Error(remembered)
|
||||
}
|
||||
try {
|
||||
return await ghExecFileAsync(args, ghOptions)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
if (isGhCwdRepoResolutionFailure(message)) {
|
||||
await rememberGhCwdResolutionFailure(context, message)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function listRecentWorkItems(
|
||||
repoPath: string,
|
||||
issueOwnerRepo: OwnerRepo | null,
|
||||
@@ -1014,7 +1046,8 @@ async function listRecentWorkItems(
|
||||
noCache?: boolean,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<PartialWorkItemsResult> {
|
||||
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
|
||||
const repoContext = githubRepoContext(repoPath, connectionId, localGitOptions)
|
||||
const ghOptions = ghRepoExecOptions(repoContext)
|
||||
const requiresExplicitRepo = Boolean(connectionId)
|
||||
const restCacheArgs = noCache ? [] : ['--cache', '120s']
|
||||
assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo })
|
||||
@@ -1034,7 +1067,8 @@ async function listRecentWorkItems(
|
||||
)
|
||||
: requiresExplicitRepo
|
||||
? Promise.resolve({ stdout: '[]' })
|
||||
: ghExecFileAsync(
|
||||
: ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'issue',
|
||||
'list',
|
||||
@@ -1058,7 +1092,8 @@ async function listRecentWorkItems(
|
||||
)
|
||||
: requiresExplicitRepo
|
||||
? Promise.resolve({ stdout: '[]' })
|
||||
: ghExecFileAsync(
|
||||
: ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'pr',
|
||||
'list',
|
||||
@@ -1130,7 +1165,8 @@ async function listRecentWorkItems(
|
||||
// effectively unusable for the feature — reject-all matches reality. If
|
||||
// non-GitHub remotes ever grow source metadata, revisit this symmetry.
|
||||
const [issuesResult, prsResult] = await Promise.all([
|
||||
ghExecFileAsync(
|
||||
ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'issue',
|
||||
'list',
|
||||
@@ -1143,7 +1179,8 @@ async function listRecentWorkItems(
|
||||
],
|
||||
ghOptions
|
||||
),
|
||||
ghExecFileAsync(
|
||||
ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'pr',
|
||||
'list',
|
||||
@@ -1180,7 +1217,8 @@ async function listQueriedWorkItems(
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<PartialWorkItemsResult> {
|
||||
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
|
||||
const repoContext = githubRepoContext(repoPath, connectionId, localGitOptions)
|
||||
const ghOptions = ghRepoExecOptions(repoContext)
|
||||
const requiresExplicitRepo = Boolean(connectionId)
|
||||
assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo })
|
||||
const hasPrOnlyFilter =
|
||||
@@ -1209,7 +1247,9 @@ async function listQueriedWorkItems(
|
||||
before
|
||||
})
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(args, ghOptions)
|
||||
const { stdout } = issueOwnerRepo
|
||||
? await ghExecFileAsync(args, ghOptions)
|
||||
: await ghCwdResolvedExec(repoContext, args, ghOptions)
|
||||
return {
|
||||
items: (JSON.parse(stdout) as Record<string, unknown>[]).map(mapIssueWorkItem)
|
||||
}
|
||||
@@ -1234,7 +1274,9 @@ async function listQueriedWorkItems(
|
||||
before
|
||||
})
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(args, ghOptions)
|
||||
const { stdout } = prOwnerRepo
|
||||
? await ghExecFileAsync(args, ghOptions)
|
||||
: await ghCwdResolvedExec(repoContext, args, ghOptions)
|
||||
const mapped = (JSON.parse(stdout) as Record<string, unknown>[]).map((item) =>
|
||||
mapPullRequestWorkItem(item, prOwnerRepo)
|
||||
)
|
||||
@@ -1398,6 +1440,9 @@ async function countWorkItemsForQuery(
|
||||
],
|
||||
ghOptions
|
||||
)
|
||||
// Why: over-counts gh cache hits, which is the safe direction — the search
|
||||
// bucket is only 30/min and the next probe corrects the estimate.
|
||||
noteRateLimitSpend('search')
|
||||
return Number.parseInt(stdout.trim(), 10) || 0
|
||||
}
|
||||
|
||||
@@ -1453,6 +1498,15 @@ export async function countWorkItems(
|
||||
const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null
|
||||
const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery()
|
||||
|
||||
// Why: counts are decorative (pagination totals). The search bucket is only
|
||||
// 30/min, so a multi-repo Tasks page must stop counting when the budget is
|
||||
// gone instead of converting the remaining repos into 403 spawns. getRateLimit
|
||||
// is 30s-cached and single-flight, so priming here is one spawn per window.
|
||||
await getRateLimit()
|
||||
if (rateLimitGuard('search').blocked) {
|
||||
return 0
|
||||
}
|
||||
|
||||
await acquire()
|
||||
try {
|
||||
if (sameOwnerRepo(issueOwnerRepo, prOwnerRepo)) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { readLocalGitConfigSignatureMock } = vi.hoisted(() => ({
|
||||
readLocalGitConfigSignatureMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./local-git-config-signature', () => ({
|
||||
readLocalGitConfigSignature: readLocalGitConfigSignatureMock
|
||||
}))
|
||||
|
||||
import {
|
||||
_resetGhCwdRepoNegativeCache,
|
||||
getRememberedGhCwdResolutionFailure,
|
||||
isGhCwdRepoResolutionFailure,
|
||||
rememberGhCwdResolutionFailure
|
||||
} from './gh-cwd-repo-negative-cache'
|
||||
|
||||
const context = { repoPath: '/repo', connectionId: null }
|
||||
|
||||
afterEach(() => {
|
||||
_resetGhCwdRepoNegativeCache()
|
||||
readLocalGitConfigSignatureMock.mockReset()
|
||||
})
|
||||
|
||||
describe('isGhCwdRepoResolutionFailure', () => {
|
||||
it('matches gh cwd-resolution failures only', () => {
|
||||
expect(isGhCwdRepoResolutionFailure('Command failed: gh\nno git remotes found')).toBe(true)
|
||||
expect(
|
||||
isGhCwdRepoResolutionFailure(
|
||||
'none of the git remotes configured for this repository point to a known GitHub host'
|
||||
)
|
||||
).toBe(true)
|
||||
expect(isGhCwdRepoResolutionFailure('gh: API rate limit exceeded (HTTP 403)')).toBe(false)
|
||||
expect(isGhCwdRepoResolutionFailure('gh: Not Found (HTTP 404)')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('remembered failures', () => {
|
||||
it('serves the remembered failure while the config signature is unchanged', async () => {
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig-1')
|
||||
await rememberGhCwdResolutionFailure(context, 'no git remotes found')
|
||||
await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBe('no git remotes found')
|
||||
})
|
||||
|
||||
it('invalidates when the git config signature changes (remote added)', async () => {
|
||||
readLocalGitConfigSignatureMock.mockResolvedValueOnce('sig-1')
|
||||
await rememberGhCwdResolutionFailure(context, 'no git remotes found')
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig-2')
|
||||
await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBeNull()
|
||||
// The stale entry is gone, not just skipped.
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig-1')
|
||||
await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('separates repos and runtimes by cache key', async () => {
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig')
|
||||
await rememberGhCwdResolutionFailure(context, 'no git remotes found')
|
||||
await expect(
|
||||
getRememberedGhCwdResolutionFailure({ repoPath: '/other-repo', connectionId: null })
|
||||
).resolves.toBeNull()
|
||||
await expect(
|
||||
getRememberedGhCwdResolutionFailure({ repoPath: '/repo', connectionId: 'ssh-1' })
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
import { readLocalGitConfigSignature } from './local-git-config-signature'
|
||||
import type { GitHubRepoContext } from './github-repository-identity'
|
||||
|
||||
/**
|
||||
* Negative cache for repos where gh's cwd-based repo resolution fails
|
||||
* ("no git remotes found" etc). Orca only falls back to cwd resolution when
|
||||
* it could not resolve an owner/repo itself, so for a remote-less repo the
|
||||
* failure is deterministic — yet the Tasks page re-spawned gh for every such
|
||||
* repo on every refresh (×90 repos in the reported storm). Remember the
|
||||
* failure and re-throw it without a subprocess until the repo's git config
|
||||
* changes (signature check) or the TTL lapses.
|
||||
*/
|
||||
const NEGATIVE_CACHE_TTL_MS = 5 * 60_000
|
||||
const MAX_ENTRIES = 512
|
||||
|
||||
type NegativeCacheEntry = {
|
||||
message: string
|
||||
configSignature: string | undefined
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const entries = new Map<string, NegativeCacheEntry>()
|
||||
|
||||
function negativeCacheKey(context: GitHubRepoContext): string {
|
||||
const runtimeKey = context.connectionId ?? `local:${context.wslDistro ?? 'host'}`
|
||||
return `${runtimeKey}\0${context.repoPath}`
|
||||
}
|
||||
|
||||
export function isGhCwdRepoResolutionFailure(text: string): boolean {
|
||||
const s = text.toLowerCase()
|
||||
return (
|
||||
s.includes('no git remotes found') ||
|
||||
s.includes('not a git repository') ||
|
||||
s.includes('unable to determine base repository') ||
|
||||
s.includes('none of the git remotes configured')
|
||||
)
|
||||
}
|
||||
|
||||
export async function getRememberedGhCwdResolutionFailure(
|
||||
context: GitHubRepoContext
|
||||
): Promise<string | null> {
|
||||
const key = negativeCacheKey(context)
|
||||
const entry = entries.get(key)
|
||||
if (!entry) {
|
||||
return null
|
||||
}
|
||||
if (entry.expiresAt <= Date.now()) {
|
||||
entries.delete(key)
|
||||
return null
|
||||
}
|
||||
// Why: adding a remote is the way out of this failure; the config signature
|
||||
// (mtime/size of the repo's git config chain) changes when that happens.
|
||||
const signature = await readLocalGitConfigSignature(context)
|
||||
if (signature !== entry.configSignature) {
|
||||
entries.delete(key)
|
||||
return null
|
||||
}
|
||||
return entry.message
|
||||
}
|
||||
|
||||
export async function rememberGhCwdResolutionFailure(
|
||||
context: GitHubRepoContext,
|
||||
message: string
|
||||
): Promise<void> {
|
||||
const configSignature = await readLocalGitConfigSignature(context)
|
||||
entries.set(negativeCacheKey(context), {
|
||||
message,
|
||||
configSignature,
|
||||
expiresAt: Date.now() + NEGATIVE_CACHE_TTL_MS
|
||||
})
|
||||
while (entries.size > MAX_ENTRIES) {
|
||||
const oldest = entries.keys().next()
|
||||
if (oldest.done) {
|
||||
break
|
||||
}
|
||||
entries.delete(oldest.value)
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal — test-only */
|
||||
export function _resetGhCwdRepoNegativeCache(): void {
|
||||
entries.clear()
|
||||
}
|
||||
@@ -4,6 +4,14 @@ import type { ClassifiedError } from '../../shared/types'
|
||||
// patterns to typed errors so callers can show user-friendly messages.
|
||||
export function classifyGhError(stderr: string): ClassifiedError {
|
||||
const s = stderr.toLowerCase()
|
||||
// Why: primary rate-limit errors also carry "HTTP 403" — check rate limit
|
||||
// first so they don't misclassify as a token-scope problem.
|
||||
if (s.includes('rate limit')) {
|
||||
return {
|
||||
type: 'rate_limited',
|
||||
message: 'GitHub rate limit hit. Try again in a few minutes.'
|
||||
}
|
||||
}
|
||||
if (s.includes('http 403') || s.includes('resource not accessible')) {
|
||||
return {
|
||||
type: 'permission_denied',
|
||||
@@ -19,12 +27,6 @@ export function classifyGhError(stderr: string): ClassifiedError {
|
||||
if (s.includes('http 422') || s.includes('validation failed')) {
|
||||
return { type: 'validation_error', message: `Invalid update — ${stderr.trim()}` }
|
||||
}
|
||||
if (s.includes('rate limit')) {
|
||||
return {
|
||||
type: 'rate_limited',
|
||||
message: 'GitHub rate limit hit. Try again in a few minutes.'
|
||||
}
|
||||
}
|
||||
if (
|
||||
s.includes('timeout') ||
|
||||
s.includes('no such host') ||
|
||||
|
||||
@@ -20,6 +20,13 @@ import type {
|
||||
} from '../../shared/types'
|
||||
import { acquire, release } from './gh-utils'
|
||||
import { ghExecFileAsync } from '../git/runner'
|
||||
import {
|
||||
clearGhRateLimitBlock,
|
||||
getGhRateLimitBlockedUntilMs,
|
||||
recordGhPrimaryRateLimit,
|
||||
registerGhRateLimitResetProbe,
|
||||
type GhRateLimitBucket
|
||||
} from '../git/gh-rate-limit-breaker'
|
||||
|
||||
// Why: GitHub explicitly states `GET /rate_limit` does NOT count against
|
||||
// any bucket, so the only reason to cache is to avoid spawning a `gh`
|
||||
@@ -93,6 +100,18 @@ export function rateLimitGuard(bucket: RateLimitBucketKind):
|
||||
limit: number
|
||||
resetAt: number
|
||||
} {
|
||||
// Why: the runner-level breaker learns about exhaustion from actual 403s,
|
||||
// which can happen long before (or without) a snapshot probe — e.g. quota
|
||||
// burned by another tool on the same account.
|
||||
const breakerBlockedUntilMs = getGhRateLimitBlockedUntilMs(bucket)
|
||||
if (breakerBlockedUntilMs !== null) {
|
||||
return {
|
||||
blocked: true,
|
||||
remaining: 0,
|
||||
limit: cached?.[bucket].limit ?? 0,
|
||||
resetAt: Math.ceil(breakerBlockedUntilMs / 1000)
|
||||
}
|
||||
}
|
||||
if (!cached) {
|
||||
return { blocked: false }
|
||||
}
|
||||
@@ -103,6 +122,11 @@ export function rateLimitGuard(bucket: RateLimitBucketKind):
|
||||
: bucket === 'graphql'
|
||||
? MIN_REMAINING_GRAPHQL
|
||||
: MIN_REMAINING_SEARCH
|
||||
// Why: a snapshot from before the bucket's reset time describes a window
|
||||
// that has already ended — fail open rather than blocking on stale data.
|
||||
if (b.resetAt * 1000 <= Date.now()) {
|
||||
return { blocked: false }
|
||||
}
|
||||
// Why: only block when we have a positive limit (limit:0 means "unknown" per
|
||||
// parseBucket fallback — don't block on missing data, that would brick the
|
||||
// app on a single bad rate_limit response).
|
||||
@@ -130,10 +154,63 @@ export function noteRateLimitSpend(bucket: RateLimitBucketKind, cost = 1): void
|
||||
}
|
||||
}
|
||||
|
||||
// Why: when the runner's breaker trips it only knows "blocked", not for how
|
||||
// long. `gh api rate_limit` is exempt from limits, so one forced probe turns
|
||||
// the fallback block into the bucket's real reset time (or clears a block
|
||||
// that a stale fallback would otherwise keep alive). Single-flight: a 90-repo
|
||||
// 403 burst must refine once, not 90 times.
|
||||
let resetRefinementInFlight: Promise<void> | null = null
|
||||
|
||||
function refineBreakerFromSnapshot(): void {
|
||||
if (resetRefinementInFlight) {
|
||||
return
|
||||
}
|
||||
resetRefinementInFlight = (async () => {
|
||||
try {
|
||||
const result = await getRateLimit({ force: true })
|
||||
if (!result.ok) {
|
||||
return
|
||||
}
|
||||
for (const bucket of ['core', 'search', 'graphql'] as GhRateLimitBucket[]) {
|
||||
const b = result.snapshot[bucket]
|
||||
if (b.limit > 0 && b.remaining <= 0) {
|
||||
recordGhPrimaryRateLimit(bucket, b.resetAt * 1000)
|
||||
} else if (b.limit > 0) {
|
||||
clearGhRateLimitBlock(bucket)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
resetRefinementInFlight = null
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
registerGhRateLimitResetProbe(() => refineBreakerFromSnapshot())
|
||||
|
||||
// Why: a 90-repo fan-out that primes the guard concurrently must resolve to
|
||||
// one `gh api rate_limit` spawn, not one per repo — the TTL cache alone can't
|
||||
// dedupe calls that all start before the first probe lands.
|
||||
let probeInFlight: Promise<GetRateLimitResult> | null = null
|
||||
|
||||
export async function getRateLimit(options?: { force?: boolean }): Promise<GetRateLimitResult> {
|
||||
if (!options?.force && cached && Date.now() - cached.fetchedAt < RATE_LIMIT_CACHE_TTL_MS) {
|
||||
return { ok: true, snapshot: cached }
|
||||
}
|
||||
if (!options?.force && probeInFlight) {
|
||||
return probeInFlight
|
||||
}
|
||||
const probe = fetchRateLimitSnapshot()
|
||||
probeInFlight = probe
|
||||
try {
|
||||
return await probe
|
||||
} finally {
|
||||
if (probeInFlight === probe) {
|
||||
probeInFlight = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRateLimitSnapshot(): Promise<GetRateLimitResult> {
|
||||
await acquire()
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(['api', 'rate_limit'], { encoding: 'utf-8' })
|
||||
|
||||
Reference in New Issue
Block a user