Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 60 additions & 9 deletions src/lib/github/github-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -251,36 +252,86 @@ type SearchPaginateParams<TNode> = {
| 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<TNode>(
executor: GitHubQueryExecutor,
params: SearchPaginateParams<TNode>,
): Promise<Array<TNode>> {
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<TNode> = [];
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) {
break;
}

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<string, unknown>, Record<string, unknown>>({
operationName: params.operationName,
query: params.query,
variables,
});

let data: Record<string, unknown>;
try {
data = await executor.execute<Record<string, unknown>, Record<string, unknown>>({
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) {
Expand Down
87 changes: 81 additions & 6 deletions src/lib/github/github-graphql-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}
Expand Down Expand Up @@ -182,13 +188,15 @@ export class GitHubApiError extends Error {
readonly rateLimit: RateLimitSnapshot;
readonly retriable: boolean;
readonly retryAfterMs?: number;
readonly operationName?: string;

constructor(params: {
message: string;
kind: GitHubErrorKind;
status: number;
rateLimit: RateLimitSnapshot;
retryAfterMs?: number;
operationName?: string;
}) {
super(params.message);
this.name = "GitHubApiError";
Expand All @@ -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;
}
}

Expand Down Expand Up @@ -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<TVariables extends Record<string, unknown>> = {
operationName: string;
query: string;
variables: TVariables;
skipRetryOnPageSizeError?: boolean;
};

function summarizeNonJsonBody(rawText: string): string {
const titleMatch = /<title[^>]*>([\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;
Expand Down Expand Up @@ -290,8 +320,11 @@ export class GitHubGraphQLClient {
await this.applyAdaptiveDelay();
return await this.executeOnce<TData, TVariables>(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;
Expand All @@ -311,9 +344,44 @@ export class GitHubGraphQLClient {
kind: "UNKNOWN",
status: 500,
rateLimit: this.lastRateLimit,
operationName: params.operationName,
});
}

private async parseResponsePayload<TData>(
response: Response,
operationName: string,
rateLimit: RateLimitSnapshot,
): Promise<GraphQLSuccessResponse<TData>> {
if (typeof response.text !== "function") {
return (await response.json()) as GraphQLSuccessResponse<TData>;
}

const rawText = await response.text();
try {
return JSON.parse(rawText) as GraphQLSuccessResponse<TData>;
} 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<TData, TVariables extends Record<string, unknown>>(
params: ExecuteQueryParams<TVariables>,
): Promise<TData> {
Expand All @@ -333,7 +401,11 @@ export class GitHubGraphQLClient {
const rateLimit = parseRateLimitHeaders(response.headers);
this.lastRateLimit = rateLimit;

const payload = (await response.json()) as GraphQLSuccessResponse<TData>;
const payload = await this.parseResponsePayload<TData>(
response,
params.operationName,
rateLimit,
);
if (!response.ok || (payload.errors && payload.errors.length > 0)) {
const kind = classifyGitHubError({
status: response.status,
Expand All @@ -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,
});
}

Expand Down
Loading
Loading