Files
orca/src/main/gitea/client.ts
T
fb5bc4fd24 fix(gitea): share and cache the /pulls scan so card refreshes can't hammer a self-hosted forge (#8858)
* fix(gitea): share and cache the /pulls scan so card refreshes can't hammer a self-hosted forge

Each worktree card resolved its branch by paginating the repo's full
/pulls listing (state=all, up to 5 pages) independently, with a 5s
timeout. Gitea/Forgejo have no head-branch filter, self-hosted Forgejo
takes ~5s per page (it loads reviewer data per PR), and a push event
refreshes every card at once — so one repo turned into hundreds of
near-simultaneous requests whose responses were aborted right as they
completed, and the burst OOM-killed a 512Mi Forgejo pod (#8807).

- Share one in-flight /pulls scan per repo across concurrent branch
  lookups and cache the result for 30s, so a burst costs a single page
  walk instead of one per worktree.
- Raise the list-scan timeout to 15s so slow-but-successful pages are
  used instead of discarded and retried.
- Invalidate the cached scan after Orca itself creates a PR (and before
  the post-create fallback lookup) so the new PR is seen immediately.

Fixes #8807

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(gitea): don't let an in-flight scan re-cache a listing from before an invalidation

Review feedback: if a PR is created while a card-refresh scan is in
flight, the invalidation cleared the cache but the scan then finished
and re-cached the pre-create listing, hiding the new PR for a full TTL.
Track a per-repo generation: invalidation bumps it (and drops the
in-flight promise), and a scan only writes the cache when its generation
is still current.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(gitea): bound PR scan cache and retry failures

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com>
Co-authored-by: Orca <help@stably.ai>
2026-07-15 13:39:16 -07:00

283 lines
7.9 KiB
TypeScript

import {
deriveGiteaCommitStatus,
mapGiteaPullRequest,
type GiteaPullRequestInfo,
type RawGiteaCombinedStatus,
type RawGiteaPullRequest
} from './pull-request-mappers'
import { getGiteaRepoRef, type GiteaRepoRef } from './repository-ref'
import { invalidateGiteaPullRequestScan, scanGiteaPullRequests } from './pull-request-scan-cache'
import {
getHostedReviewLocalGitOptions,
type HostedReviewExecutionOptions
} from '../source-control/hosted-review-git-options'
const REQUEST_TIMEOUT_MS = 5000
// Why: self-hosted Forgejo can take ~5s to serve one /pulls page (it loads
// reviewer data per PR). The default 5s cap aborted responses right as they
// completed, so the work was discarded and retried on the next refresh (#8807).
const PULL_REQUEST_LIST_TIMEOUT_MS = 15_000
const PULL_REQUEST_PAGE_LIMIT = 50
const MAX_PULL_REQUEST_PAGES = 5
type GiteaAuthConfig = {
apiBaseUrl: string | null
token: string | null
}
export type GiteaAuthStatus = {
configured: boolean
authenticated: boolean
account: string | null
baseUrl: string | null
tokenConfigured: boolean
}
type RequestOptions = {
searchParams?: Record<string, string | number>
timeoutMs?: number
}
function envValue(name: string): string | null {
const value = process.env[name]?.trim() ?? ''
return value.length > 0 ? value : null
}
export function normalizeGiteaApiBaseUrl(value: string): string {
const trimmed = value.trim().replace(/\/+$/, '')
return /\/api\/v1$/i.test(trimmed) ? trimmed : `${trimmed}/api/v1`
}
function getAuthConfig(): GiteaAuthConfig {
const apiBaseUrl = envValue('ORCA_GITEA_API_BASE_URL')
return {
apiBaseUrl: apiBaseUrl ? normalizeGiteaApiBaseUrl(apiBaseUrl) : null,
token: envValue('ORCA_GITEA_TOKEN')
}
}
function authHeaders(config: Pick<GiteaAuthConfig, 'token'>): Record<string, string> {
return config.token ? { Authorization: `token ${config.token}` } : {}
}
function configuredApiBaseUrl(repo: GiteaRepoRef): string {
return getAuthConfig().apiBaseUrl ?? repo.apiBaseUrl
}
function apiUrl(baseUrl: string, path: string, searchParams?: RequestOptions['searchParams']): URL {
const url = new URL(`${baseUrl.replace(/\/+$/, '')}${path}`)
if (searchParams) {
for (const [key, value] of Object.entries(searchParams)) {
url.searchParams.set(key, String(value))
}
}
return url
}
async function requestJsonAtBase<T>(
baseUrl: string,
path: string,
options: RequestOptions = {}
): Promise<T | null> {
const config = getAuthConfig()
try {
const response = await fetch(apiUrl(baseUrl, path, options.searchParams), {
headers: {
Accept: 'application/json',
...authHeaders(config)
},
signal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS)
})
if (!response.ok) {
return null
}
return (await response.json()) as T
} catch {
return null
}
}
function requestJson<T>(
repo: GiteaRepoRef,
path: string,
options: RequestOptions = {}
): Promise<T | null> {
return requestJsonAtBase(configuredApiBaseUrl(repo), path, options)
}
function encodedRepoPath(repo: GiteaRepoRef): string {
return `${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.repo)}`
}
function giteaPullRequestScanKey(repo: GiteaRepoRef): string {
return `${configuredApiBaseUrl(repo)}/${encodedRepoPath(repo)}`
}
/** Invalidate the shared /pulls scan after Orca itself creates a PR so the
* next worktree-card refresh sees it instead of a cached miss. */
export function invalidateGiteaPullRequestScanForRepo(repo: GiteaRepoRef): void {
invalidateGiteaPullRequestScan(giteaPullRequestScanKey(repo))
}
async function getCommitStatus(
repo: GiteaRepoRef,
headSha: string | undefined
): Promise<ReturnType<typeof deriveGiteaCommitStatus>> {
if (!headSha) {
return 'neutral'
}
const data = await requestJson<RawGiteaCombinedStatus>(
repo,
`/repos/${encodedRepoPath(repo)}/commits/${encodeURIComponent(headSha)}/status`
)
return deriveGiteaCommitStatus(data)
}
async function normalizePullRequest(
repo: GiteaRepoRef,
raw: RawGiteaPullRequest
): Promise<GiteaPullRequestInfo | null> {
const status = await getCommitStatus(repo, raw.head?.sha?.trim())
return mapGiteaPullRequest(raw, status)
}
function matchesBranch(raw: RawGiteaPullRequest, branchName: string): boolean {
const ref = raw.head?.ref?.trim()
if (ref === branchName) {
return true
}
const label = raw.head?.label?.trim()
return label === branchName || label?.endsWith(`:${branchName}`) === true
}
export async function getGiteaAuthStatus(): Promise<GiteaAuthStatus> {
const config = getAuthConfig()
const tokenConfigured = config.token !== null
if (!config.apiBaseUrl && !tokenConfigured) {
return {
configured: false,
authenticated: false,
account: null,
baseUrl: null,
tokenConfigured: false
}
}
if (!config.apiBaseUrl) {
return {
configured: true,
authenticated: true,
account: null,
baseUrl: null,
tokenConfigured
}
}
if (!tokenConfigured) {
const version = await requestJsonAtBase<{ version?: string }>(config.apiBaseUrl, '/version', {
timeoutMs: 4000
})
return {
configured: version !== null,
authenticated: false,
account: null,
baseUrl: config.apiBaseUrl,
tokenConfigured
}
}
const user = await requestJsonAtBase<{
login?: string | null
username?: string | null
full_name?: string | null
}>(config.apiBaseUrl, '/user', { timeoutMs: 4000 })
return {
configured: true,
authenticated: user !== null,
account: user?.login ?? user?.username ?? user?.full_name ?? null,
baseUrl: config.apiBaseUrl,
tokenConfigured
}
}
export async function getGiteaPullRequest(
repoPath: string,
prNumber: number,
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<GiteaPullRequestInfo | null> {
const repo = await getGiteaRepoRef(
repoPath,
connectionId,
getHostedReviewLocalGitOptions(options)
)
if (!repo) {
return null
}
const raw = await requestJson<RawGiteaPullRequest>(
repo,
`/repos/${encodedRepoPath(repo)}/pulls/${encodeURIComponent(String(prNumber))}`
)
return raw ? normalizePullRequest(repo, raw) : null
}
export async function getGiteaPullRequestForBranch(
repoPath: string,
branch: string,
linkedPRNumber?: number | null,
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<GiteaPullRequestInfo | null> {
const branchName = branch.replace(/^refs\/heads\//, '')
if (!branchName && linkedPRNumber == null) {
return null
}
const repo = await getGiteaRepoRef(
repoPath,
connectionId,
getHostedReviewLocalGitOptions(options)
)
if (!repo) {
return null
}
if (branchName) {
const pullRequests = await scanGiteaPullRequests(
giteaPullRequestScanKey(repo),
(page) =>
requestJson<RawGiteaPullRequest[]>(repo, `/repos/${encodedRepoPath(repo)}/pulls`, {
searchParams: {
state: 'all',
sort: 'recentupdate',
page,
limit: PULL_REQUEST_PAGE_LIMIT
},
timeoutMs: PULL_REQUEST_LIST_TIMEOUT_MS
}),
PULL_REQUEST_PAGE_LIMIT,
MAX_PULL_REQUEST_PAGES
)
const raw = pullRequests.find((item) => matchesBranch(item, branchName))
if (raw) {
return normalizePullRequest(repo, raw)
}
}
if (typeof linkedPRNumber !== 'number') {
return null
}
const raw = await requestJson<RawGiteaPullRequest>(
repo,
`/repos/${encodedRepoPath(repo)}/pulls/${encodeURIComponent(String(linkedPRNumber))}`
)
return raw ? normalizePullRequest(repo, raw) : null
}
export async function getGiteaRepoSlug(
repoPath: string,
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
): Promise<GiteaRepoRef | null> {
return getGiteaRepoRef(repoPath, connectionId, getHostedReviewLocalGitOptions(options))
}