diff --git a/src/lib/github/github-client.ts b/src/lib/github/github-client.ts index c6c5252..80dc343 100644 --- a/src/lib/github/github-client.ts +++ b/src/lib/github/github-client.ts @@ -5,8 +5,9 @@ import { type CacheStore, } from "@/lib/cache"; import { attachErrorStage, reportServerError } from "@/lib/observability"; +import { logger } from "@/lib/logger"; import { getGitHubUserStaleDays, isUserDataFresh } from "@/utils/stale"; -import { GitHubGraphQLClient } from "./github-graphql-client"; +import { GitHubGraphQLClient, isPageSizeReducibleError } from "./github-graphql-client"; import type { DiscussionNode, GitHubUserData, IssueNode, PullRequestNode, RepoNode } from "./types"; export type UserFetchMetrics = { @@ -251,21 +252,39 @@ type SearchPaginateParams = { | undefined; maxPages?: number; maxItems?: number; + adaptivePageSize?: boolean; }; const SEARCH_PAGE_SIZE = 100; +const MIN_ADAPTIVE_PAGE_SIZE = 10; const DEFAULT_MAX_SEARCH_PAGES = 10; +const MAX_ADAPTIVE_SEARCH_PAGES = 20; async function paginateSearch( executor: GitHubQueryExecutor, params: SearchPaginateParams, ): Promise> { - const maxPages = params.maxPages ?? DEFAULT_MAX_SEARCH_PAGES; + const baseMaxPages = params.maxPages ?? DEFAULT_MAX_SEARCH_PAGES; const maxItems = params.maxItems; + const adaptivePageSize = params.adaptivePageSize ?? true; const allNodes: Array = []; let cursor: string | null = null; + let currentMaxPageSize = SEARCH_PAGE_SIZE; + let successfulPages = 0; + + while (true) { + const effectiveMaxPages = + adaptivePageSize && maxItems !== undefined + ? Math.min( + MAX_ADAPTIVE_SEARCH_PAGES, + Math.max(baseMaxPages, Math.ceil(maxItems / currentMaxPageSize)), + ) + : baseMaxPages; + + if (successfulPages >= effectiveMaxPages) { + break; + } - for (let page = 0; page < maxPages; page += 1) { const remainingItems = maxItems === undefined ? undefined : Math.max(0, maxItems - allNodes.length); if (remainingItems === 0) { @@ -273,14 +292,46 @@ async function paginateSearch( } const pageSize = - remainingItems === undefined ? SEARCH_PAGE_SIZE : Math.min(SEARCH_PAGE_SIZE, remainingItems); + remainingItems === undefined + ? currentMaxPageSize + : Math.min(currentMaxPageSize, remainingItems); + const canShrinkOnGatewayError = adaptivePageSize && pageSize > MIN_ADAPTIVE_PAGE_SIZE; const variables = params.buildVariables(cursor, pageSize); - const data = await executor.execute, Record>({ - operationName: params.operationName, - query: params.query, - variables, - }); + + let data: Record; + try { + data = await executor.execute, Record>({ + operationName: params.operationName, + query: params.query, + variables, + ...(canShrinkOnGatewayError ? { skipRetryOnPageSizeError: true } : {}), + }); + } catch (error: unknown) { + if (canShrinkOnGatewayError && isPageSizeReducibleError(error)) { + const nextPageSize = Math.max(MIN_ADAPTIVE_PAGE_SIZE, Math.floor(pageSize / 2)); + if (nextPageSize < pageSize) { + logger.warn("GitHub GraphQL page size reduced after gateway/timeout error", { + operationName: params.operationName, + previousPageSize: pageSize, + nextPageSize, + status: + error !== null && typeof error === "object" && "status" in error + ? (error as { status: unknown }).status + : undefined, + kind: + error !== null && typeof error === "object" && "kind" in error + ? (error as { kind: unknown }).kind + : undefined, + }); + currentMaxPageSize = nextPageSize; + continue; + } + } + throw error; + } + + successfulPages += 1; const field = params.extractField(data); if (!field) { diff --git a/src/lib/github/github-graphql-client.ts b/src/lib/github/github-graphql-client.ts index 1ddf86c..ef41205 100644 --- a/src/lib/github/github-graphql-client.ts +++ b/src/lib/github/github-graphql-client.ts @@ -111,11 +111,17 @@ export function classifyGitHubError(input: { } if ( + input.status === 408 || + input.status === 504 || messageIncludes(messages, ["couldn't respond to your request in time", "timed out", "timeout"]) ) { return "TIMEOUT"; } + if (input.status === 429) { + return input.rateLimit.remaining === 0 ? "PRIMARY_RATE_LIMIT" : "SECONDARY_RATE_LIMIT"; + } + if (messageIncludes(messages, ["resource limits were exceeded", "resource limit exceeded"])) { return "RESOURCE_LIMIT"; } @@ -182,6 +188,7 @@ export class GitHubApiError extends Error { readonly rateLimit: RateLimitSnapshot; readonly retriable: boolean; readonly retryAfterMs?: number; + readonly operationName?: string; constructor(params: { message: string; @@ -189,6 +196,7 @@ export class GitHubApiError extends Error { status: number; rateLimit: RateLimitSnapshot; retryAfterMs?: number; + operationName?: string; }) { super(params.message); this.name = "GitHubApiError"; @@ -197,6 +205,7 @@ export class GitHubApiError extends Error { this.rateLimit = params.rateLimit; this.retriable = isRetriable(params.kind); this.retryAfterMs = params.retryAfterMs; + this.operationName = params.operationName; } } @@ -254,12 +263,33 @@ type GitHubGraphQLClientOptions = { fetchImpl?: typeof fetch; }; +export function isPageSizeReducibleError(error: unknown): boolean { + if (!(error instanceof GitHubApiError)) { + return false; + } + + return ( + error.status === 502 || + error.status === 504 || + error.status === 408 || + error.kind === "TIMEOUT" || + error.kind === "RESOURCE_LIMIT" + ); +} + type ExecuteQueryParams> = { operationName: string; query: string; variables: TVariables; + skipRetryOnPageSizeError?: boolean; }; +function summarizeNonJsonBody(rawText: string): string { + const titleMatch = /]*>([\s\S]*?)<\/title>/i.exec(rawText); + const candidate = titleMatch?.[1] ?? rawText.replace(/<[^>]+>/g, " "); + return candidate.replace(/\s+/g, " ").trim().slice(0, 160); +} + export class GitHubGraphQLClient { private readonly token: string; private readonly maxRetries: number; @@ -290,8 +320,11 @@ export class GitHubGraphQLClient { await this.applyAdaptiveDelay(); return await this.executeOnce(params); } catch (error: unknown) { - const normalizedError = this.normalizeError(error); - const shouldRetry = normalizedError.retriable && attempt < this.maxRetries; + const normalizedError = this.normalizeError(error, params.operationName); + const fastFailForPageShrink = + params.skipRetryOnPageSizeError === true && isPageSizeReducibleError(normalizedError); + const shouldRetry = + !fastFailForPageShrink && normalizedError.retriable && attempt < this.maxRetries; if (!shouldRetry) { throw normalizedError; @@ -311,9 +344,44 @@ export class GitHubGraphQLClient { kind: "UNKNOWN", status: 500, rateLimit: this.lastRateLimit, + operationName: params.operationName, }); } + private async parseResponsePayload( + response: Response, + operationName: string, + rateLimit: RateLimitSnapshot, + ): Promise> { + if (typeof response.text !== "function") { + return (await response.json()) as GraphQLSuccessResponse; + } + + const rawText = await response.text(); + try { + return JSON.parse(rawText) as GraphQLSuccessResponse; + } catch { + const snippet = summarizeNonJsonBody(rawText); + const kind = classifyGitHubError({ + status: response.status, + errors: snippet ? [{ message: snippet }] : undefined, + rateLimit, + }); + const detail = snippet + ? `(${snippet})` + : `(empty body, content-type: ${response.headers.get("content-type") ?? "unknown"})`; + + throw new GitHubApiError({ + message: `GitHub GraphQL ${operationName} returned non-JSON HTTP ${response.status} ${detail}`, + kind: kind === "UNKNOWN" && response.status >= 500 ? "NETWORK" : kind, + status: response.status, + rateLimit, + retryAfterMs: rateLimit.retryAfterSeconds ? rateLimit.retryAfterSeconds * 1000 : undefined, + operationName, + }); + } + } + private async executeOnce>( params: ExecuteQueryParams, ): Promise { @@ -333,7 +401,11 @@ export class GitHubGraphQLClient { const rateLimit = parseRateLimitHeaders(response.headers); this.lastRateLimit = rateLimit; - const payload = (await response.json()) as GraphQLSuccessResponse; + const payload = await this.parseResponsePayload( + response, + params.operationName, + rateLimit, + ); if (!response.ok || (payload.errors && payload.errors.length > 0)) { const kind = classifyGitHubError({ status: response.status, @@ -350,32 +422,35 @@ export class GitHubGraphQLClient { status: response.status, rateLimit, retryAfterMs: rateLimit.retryAfterSeconds ? rateLimit.retryAfterSeconds * 1000 : undefined, + operationName: params.operationName, }); } if (!payload.data) { throw new GitHubApiError({ - message: "GitHub GraphQL response did not include data", + message: `GitHub GraphQL ${params.operationName} response did not include data`, kind: "UNKNOWN", status: response.status, rateLimit, + operationName: params.operationName, }); } return payload.data; } - private normalizeError(error: unknown): GitHubApiError { + private normalizeError(error: unknown, operationName?: string): GitHubApiError { if (error instanceof GitHubApiError) { return error; } const message = error instanceof Error ? error.message : "Unknown network error"; return new GitHubApiError({ - message, + message: operationName ? `${operationName}: ${message}` : message, kind: "NETWORK", status: 503, rateLimit: this.lastRateLimit, + operationName, }); } diff --git a/src/lib/github/tests/github-cache.test.ts b/src/lib/github/tests/github-cache.test.ts index 6808863..aa44f26 100644 --- a/src/lib/github/tests/github-cache.test.ts +++ b/src/lib/github/tests/github-cache.test.ts @@ -1,7 +1,11 @@ import "dotenv/config"; import { afterEach, describe, expect, test, vi } from "vitest"; -import { createGitHubUserDataFetcher, type GitHubFetcherDependencies } from "@/lib/github"; +import { + createGitHubUserDataFetcher, + GitHubApiError, + type GitHubFetcherDependencies, +} from "@/lib/github"; import { DEFAULT_CACHE_NAMESPACE, DEFAULT_GITHUB_CACHE_TTL_SECONDS, @@ -628,3 +632,141 @@ describe("GitHub user data caching", () => { ).toBe(DEFAULT_CACHE_NAMESPACE); }); }); + +describe("GitHub GraphQL adaptive page-size fallback", () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + test("halves FetchUserPullRequests page size after HTTP 502 and completes pagination", async () => { + vi.stubEnv("GITHUB_PR_COUNT", "80"); + vi.spyOn(console, "warn").mockImplementation(() => {}); + + const prAttempts: Array<{ prCount: number; prCursor: string | null }> = []; + const baseExecutor = makeExecutor([]); + + const executor: GitHubFetcherDependencies["executor"] = { + async execute>(params: { + operationName: string; + query: string; + variables: TVariables; + skipRetryOnPageSizeError?: boolean; + }): Promise { + if (params.operationName !== "FetchUserPullRequests") { + return baseExecutor.execute(params); + } + + const prCount = params.variables.prCount as number; + const prCursor = (params.variables.prCursor as string | null) ?? null; + prAttempts.push({ prCount, prCursor }); + + if (prCount > 40) { + throw new GitHubApiError({ + message: + "GitHub GraphQL FetchUserPullRequests returned non-JSON HTTP 502 (502 Bad Gateway)", + kind: "NETWORK", + status: 502, + rateLimit: {}, + operationName: "FetchUserPullRequests", + }); + } + + const startIdx = prCursor === "cursor_1" ? 40 : 0; + const nodes = Array.from({ length: prCount }, (_, idx) => ({ + merged: true, + additions: 1, + deletions: 0, + title: `PR ${startIdx + idx + 1}`, + url: `https://github.com/ext/repo/pull/${startIdx + idx + 1}`, + repository: { + nameWithOwner: "ext/repo", + url: "https://github.com/ext/repo", + stargazerCount: 10, + pushedAt: "2026-05-01T00:00:00.000Z", + owner: { login: "ext" }, + languages: { edges: [] }, + }, + })); + + return { + pullRequests: { + nodes, + pageInfo: { + hasNextPage: prCursor === null, + endCursor: prCursor === null ? "cursor_1" : null, + }, + }, + } as unknown as TData; + }, + }; + + const fetcher = createGitHubUserDataFetcher({ + executor, + cacheStore: { + enabled: false, + async get() { + return undefined; + }, + async set() {}, + }, + cacheConfig: { namespace: "test", ttlSeconds: 60 }, + }); + + const userData = await fetcher("mvanhorn"); + + expect(prAttempts).toEqual([ + { prCount: 80, prCursor: null }, + { prCount: 40, prCursor: null }, + { prCount: 40, prCursor: "cursor_1" }, + ]); + expect(userData.pullRequests).toHaveLength(80); + }); + + test("stops shrinking at MIN_ADAPTIVE_PAGE_SIZE (10) and rethrows if 504 persists", async () => { + vi.stubEnv("GITHUB_PR_COUNT", "40"); + vi.spyOn(console, "warn").mockImplementation(() => {}); + + const prCounts: number[] = []; + const baseExecutor = makeExecutor([]); + + const executor: GitHubFetcherDependencies["executor"] = { + async execute>(params: { + operationName: string; + query: string; + variables: TVariables; + }): Promise { + if (params.operationName !== "FetchUserPullRequests") { + return baseExecutor.execute(params); + } + + prCounts.push(params.variables.prCount as number); + throw new GitHubApiError({ + message: "GitHub GraphQL FetchUserPullRequests returned non-JSON HTTP 504", + kind: "TIMEOUT", + status: 504, + rateLimit: {}, + operationName: "FetchUserPullRequests", + }); + }, + }; + + const fetcher = createGitHubUserDataFetcher({ + executor, + cacheStore: { + enabled: false, + async get() { + return undefined; + }, + async set() {}, + }, + cacheConfig: { namespace: "test", ttlSeconds: 60 }, + }); + + await expect(fetcher("heavyuser")).rejects.toMatchObject({ + status: 504, + kind: "TIMEOUT", + }); + expect(prCounts).toEqual([40, 20, 10]); + }); +}); diff --git a/src/lib/github/tests/github-graphql-client.test.ts b/src/lib/github/tests/github-graphql-client.test.ts index ccac709..3cd721f 100644 --- a/src/lib/github/tests/github-graphql-client.test.ts +++ b/src/lib/github/tests/github-graphql-client.test.ts @@ -164,4 +164,119 @@ describe("GitHubGraphQLClient scheduling and retry behavior", () => { }), ).rejects.toBeInstanceOf(GitHubApiError); }); + + test("preserves HTTP status, HTML title, and operationName for non-JSON error responses", async () => { + const fetchImpl: typeof fetch = async () => + new Response("502 Bad GatewayOops", { + status: 502, + headers: { "content-type": "text/html" }, + }); + + const client = new GitHubGraphQLClient({ + token: "test", + maxRetries: 0, + baseDelayMs: 0, + fetchImpl, + }); + + await expect( + client.execute<{ viewer: { login: string } }, Record>({ + operationName: "FetchUserPullRequests", + query: "query FetchUserPullRequests { viewer { login } }", + variables: {}, + }), + ).rejects.toMatchObject({ + name: "GitHubApiError", + kind: "NETWORK", + status: 502, + operationName: "FetchUserPullRequests", + message: "GitHub GraphQL FetchUserPullRequests returned non-JSON HTTP 502 (502 Bad Gateway)", + }); + }); + + test("classifies HTTP 504 HTML gateway timeout as TIMEOUT", async () => { + const fetchImpl: typeof fetch = async () => + new Response("504 Gateway Time-out", { + status: 504, + headers: { "content-type": "text/html" }, + }); + + const client = new GitHubGraphQLClient({ + token: "test", + maxRetries: 0, + baseDelayMs: 0, + fetchImpl, + }); + + await expect( + client.execute<{ viewer: { login: string } }, Record>({ + operationName: "FetchUserPullRequests", + query: "query FetchUserPullRequests { viewer { login } }", + variables: {}, + }), + ).rejects.toMatchObject({ + name: "GitHubApiError", + kind: "TIMEOUT", + status: 504, + operationName: "FetchUserPullRequests", + }); + }); + + test("skipRetryOnPageSizeError skips retries on 502 but still retries rate limits", async () => { + let gatewayCalls = 0; + const gatewayClient = new GitHubGraphQLClient({ + token: "test", + maxRetries: 2, + baseDelayMs: 0, + fetchImpl: async () => { + gatewayCalls += 1; + return new Response("502 Bad Gateway", { status: 502 }); + }, + }); + + await expect( + gatewayClient.execute({ + operationName: "FetchUserPullRequests", + query: "query FetchUserPullRequests { viewer { login } }", + variables: {}, + skipRetryOnPageSizeError: true, + }), + ).rejects.toMatchObject({ status: 502 }); + expect(gatewayCalls).toBe(1); + + let rateLimitCalls = 0; + const rateLimitClient = new GitHubGraphQLClient({ + token: "test", + maxRetries: 1, + baseDelayMs: 0, + fetchImpl: async () => { + rateLimitCalls += 1; + if (rateLimitCalls === 1) { + return new Response( + JSON.stringify({ errors: [{ message: "You have exceeded a secondary rate limit." }] }), + { + status: 403, + headers: { "content-type": "application/json", "retry-after": "1" }, + }, + ); + } + return new Response(JSON.stringify({ data: { viewer: { login: "octocat" } } }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }); + + const data = await rateLimitClient.execute< + { viewer: { login: string } }, + Record + >({ + operationName: "FetchUserPullRequests", + query: "query FetchUserPullRequests { viewer { login } }", + variables: {}, + skipRetryOnPageSizeError: true, + }); + expect(data.viewer.login).toBe("octocat"); + expect(rateLimitCalls).toBe(2); + }); }); diff --git a/src/lib/observability/error-classifier.ts b/src/lib/observability/error-classifier.ts index 1bf3ca5..7aff786 100644 --- a/src/lib/observability/error-classifier.ts +++ b/src/lib/observability/error-classifier.ts @@ -250,10 +250,12 @@ export function classifyError(error: unknown, meta: ClassifyErrorContext): Categ let code: CategorizedErrorCode = "UNEXPECTED_ERROR"; let rateLimit: CategorizedRateLimit | undefined; let httpStatus = meta.httpStatus; + let operationName: string | undefined; if (innerError instanceof GitHubApiError) { code = mapGitHubKindToCode(innerError.kind); httpStatus = httpStatus ?? innerError.status; + operationName = innerError.operationName; rateLimit = { ...innerError.rateLimit, ...(innerError.retryAfterMs !== undefined @@ -309,6 +311,14 @@ export function classifyError(error: unknown, meta: ClassifyErrorContext): Categ const severity = resolveDefaultSeverity(code, meta); const stack = extractErrorStack(innerError, error); + const mergedContext = + meta.context || operationName + ? { + ...meta.context, + ...(operationName ? { operationName } : {}), + } + : undefined; + return { fingerprint: buildFingerprint({ source: meta.source, @@ -330,7 +340,7 @@ export function classifyError(error: unknown, meta: ClassifyErrorContext): Categ ...(pgCode ? { pgCode } : {}), ...(httpStatus !== undefined ? { httpStatus } : {}), ...(stack ? { stack } : {}), - ...(meta.context ? { context: meta.context } : {}), + ...(mergedContext ? { context: mergedContext } : {}), occurredAt: new Date().toISOString(), }; } diff --git a/src/lib/observability/tests/observability.test.ts b/src/lib/observability/tests/observability.test.ts index 2c46dbe..9efec0b 100644 --- a/src/lib/observability/tests/observability.test.ts +++ b/src/lib/observability/tests/observability.test.ts @@ -28,6 +28,7 @@ describe("observability error classification and reporting", () => { status: 403, rateLimit: { limit: 5000, remaining: 0, used: 5000, resetAt: 1700000000 }, retryAfterMs: 45_000, + operationName: "FetchUserPullRequests", }), "pull_requests", ); @@ -45,6 +46,7 @@ describe("observability error classification and reporting", () => { expect(categorized.target?.username).toBe("torvalds"); expect(categorized.httpStatus).toBe(403); expect(categorized.requestId).toBe("req_abc123"); + expect(categorized.context).toEqual({ operationName: "FetchUserPullRequests" }); expect(categorized.rateLimit).toEqual({ limit: 5000, remaining: 0,