import * as v from 'valibot'; import { encodePathSegment, githubFetch, githubGraphqlFetch, githubTokenFingerprint, } from './client'; import { githubIssueCommentApiResponseSchema, githubIssueCommentsApiResponseSchema, githubReviewThreadNodeGraphqlResponseSchema, githubReviewThreadCommentsGraphqlResponseSchema, githubReviewThreadsGraphqlResponseSchema, pullRequestReviewThreadNodeQuery, pullRequestReviewSurfaceThreadsQuery, pullRequestReviewThreadsQuery, reviewThreadCommentsQuery, } from './schemas'; import type { GitHubPullRequestComment, GitHubPullRequestReviewThread, GitHubPullRequestReviewThreadComment, GitHubReviewThreadCommentGraphqlNode, GitHubReviewThreadGraphqlNode, } from './schemas'; import type { PullRequestEventFetchBudget } from './event-budget'; const reviewSurfaceCacheTtlMs = 15_000; const reviewSurfaceCacheMaxEntries = 16; const reviewSurfaceCache = new Map(); const reviewSurfaceRequestsInFlight = new Map< string, Promise >(); const reviewSurfaceTargetEpochs = new Map(); export type ReviewThreadsWithMetadata = { reviewThreads: GitHubPullRequestReviewThread[]; truncated: boolean; headSha: string | null; }; type CachedReviewSurfaceThreads = { targetKey: string; expiresAt: number; value: ReviewThreadsWithMetadata; }; export async function postPullRequestComment(options: { token: string; owner: string; repo: string; number: number; body: string; }): Promise { const response = await githubFetch( options.token, `https://api.github.com/repos/${encodePathSegment(options.owner)}/${encodePathSegment(options.repo)}/issues/${options.number}/comments`, { method: 'POST', body: JSON.stringify({ body: options.body }), }, ); const data = v.parse( githubIssueCommentApiResponseSchema, await response.json(), ); return { id: data.id, nodeId: data.node_id ?? null, url: data.html_url, authorLogin: data.user?.login ?? null, authorType: data.user?.type ?? null, authorIsBot: data.user?.type === undefined ? undefined : data.user.type === 'Bot', body: data.body, createdAt: data.created_at, updatedAt: data.updated_at, }; } export async function listPullRequestComments(options: { token: string; owner: string; repo: string; number: number; }): Promise { const comments: GitHubPullRequestComment[] = []; for (let page = 1; page <= 100; page += 1) { const response = await githubFetch( options.token, `https://api.github.com/repos/${encodePathSegment(options.owner)}/${encodePathSegment(options.repo)}/issues/${options.number}/comments?per_page=100&page=${page}`, ); const data = v.parse( githubIssueCommentsApiResponseSchema, await response.json(), ); comments.push(...data.map(pullRequestCommentFromApi)); if (data.length < 100) return comments; } throw new Error( 'Pull request has more than 10,000 comments; refusing an incomplete idempotency check.', ); } export async function listPullRequestCommentsWithMetadata(options: { token: string; owner: string; repo: string; number: number; eventBudget?: PullRequestEventFetchBudget; }): Promise<{ comments: GitHubPullRequestComment[]; truncated: boolean; }> { const comments: GitHubPullRequestComment[] = []; for (let page = 1; page <= 5; page += 1) { if (!(options.eventBudget?.canFetch('conversation_comments') ?? true)) { return { comments, truncated: true }; } const response = await githubFetch( options.token, `https://api.github.com/repos/${encodePathSegment(options.owner)}/${encodePathSegment(options.repo)}/issues/${options.number}/comments?per_page=100&page=${page}`, ); const data = v.parse( githubIssueCommentsApiResponseSchema, await response.json(), ); for (const item of data.map(pullRequestCommentFromApi)) { if (options.eventBudget?.admit('conversation_comments', item) === false) { return { comments, truncated: true }; } comments.push(item); } if (data.length < 100) return { comments, truncated: false }; } return { comments, truncated: true }; } function pullRequestCommentFromApi( data: v.InferOutput, ): GitHubPullRequestComment { return { id: data.id, nodeId: data.node_id ?? null, url: data.html_url, authorLogin: data.user?.login ?? null, authorType: data.user?.type ?? null, authorIsBot: data.user?.type === undefined ? undefined : data.user.type === 'Bot', body: data.body, createdAt: data.created_at, updatedAt: data.updated_at, }; } export async function fetchPullRequestReviewThreads(options: { token: string; owner: string; repo: string; number: number; signal?: AbortSignal; }): Promise { return (await fetchPullRequestReviewThreadsWithMetadata(options)) .reviewThreads; } export async function fetchPullRequestReviewThreadsWithMetadata(options: { token: string; owner: string; repo: string; number: number; signal?: AbortSignal; eventBudget?: PullRequestEventFetchBudget; }): Promise<{ reviewThreads: GitHubPullRequestReviewThread[]; truncated: boolean; headSha: string | null; }> { return fetchReviewThreadsWithQuery(options, pullRequestReviewThreadsQuery); } export async function fetchPullRequestReviewSurfaceThreadsWithMetadata(options: { token: string; owner: string; repo: string; number: number; signal?: AbortSignal; }): Promise { const targetKey = reviewSurfaceTargetKey(options); const cacheKey = `${targetKey}\u0000${githubTokenFingerprint(options.token)}`; const cached = reviewSurfaceCache.get(cacheKey); if (cached && cached.expiresAt > Date.now()) { reviewSurfaceCache.delete(cacheKey); reviewSurfaceCache.set(cacheKey, cached); return cached.value; } if (cached) reviewSurfaceCache.delete(cacheKey); if (!options.signal) { const existing = reviewSurfaceRequestsInFlight.get(cacheKey); if (existing) return existing; const request = fetchAndCacheReviewSurfaceThreads( options, targetKey, cacheKey, ).finally(() => { if (reviewSurfaceRequestsInFlight.get(cacheKey) === request) { reviewSurfaceRequestsInFlight.delete(cacheKey); } }); reviewSurfaceRequestsInFlight.set(cacheKey, request); return request; } return fetchAndCacheReviewSurfaceThreads(options, targetKey, cacheKey); } async function fetchAndCacheReviewSurfaceThreads( options: Parameters< typeof fetchPullRequestReviewSurfaceThreadsFreshWithMetadata >[0], targetKey: string, cacheKey: string, ) { const targetEpoch = reviewSurfaceTargetEpochs.get(targetKey) ?? 0; const value = await fetchPullRequestReviewSurfaceThreadsFreshWithMetadata(options); if ((reviewSurfaceTargetEpochs.get(targetKey) ?? 0) === targetEpoch) { storeReviewSurfaceThreads(cacheKey, { targetKey, expiresAt: Date.now() + reviewSurfaceCacheTtlMs, value, }); } return value; } export async function fetchPullRequestReviewSurfaceThreadsFreshWithMetadata(options: { token: string; owner: string; repo: string; number: number; signal?: AbortSignal; }): Promise { return fetchReviewThreadsWithQuery( options, pullRequestReviewSurfaceThreadsQuery, ); } export function invalidatePullRequestReviewSurfaceThreadCache(options: { owner: string; repo: string; number: number; }) { const targetKey = reviewSurfaceTargetKey(options); reviewSurfaceTargetEpochs.set( targetKey, (reviewSurfaceTargetEpochs.get(targetKey) ?? 0) + 1, ); for (const [key, cached] of reviewSurfaceCache) { if (cached.targetKey === targetKey) reviewSurfaceCache.delete(key); } for (const key of reviewSurfaceRequestsInFlight.keys()) { if (key.startsWith(`${targetKey}\u0000`)) { reviewSurfaceRequestsInFlight.delete(key); } } } export function clearPullRequestReviewSurfaceThreadCache() { reviewSurfaceCache.clear(); reviewSurfaceRequestsInFlight.clear(); reviewSurfaceTargetEpochs.clear(); } function storeReviewSurfaceThreads( key: string, value: CachedReviewSurfaceThreads, ) { const now = Date.now(); for (const [cachedKey, cached] of reviewSurfaceCache) { if (cached.expiresAt <= now) reviewSurfaceCache.delete(cachedKey); } reviewSurfaceCache.delete(key); reviewSurfaceCache.set(key, value); while (reviewSurfaceCache.size > reviewSurfaceCacheMaxEntries) { const oldestKey = reviewSurfaceCache.keys().next().value; if (oldestKey === undefined) break; reviewSurfaceCache.delete(oldestKey); } } function reviewSurfaceTargetKey(options: { owner: string; repo: string; number: number; }) { return [ options.owner.toLowerCase(), options.repo.toLowerCase(), options.number, ].join('\u0000'); } async function fetchReviewThreadsWithQuery( options: { token: string; owner: string; repo: string; number: number; signal?: AbortSignal; eventBudget?: PullRequestEventFetchBudget; }, query: string, ): Promise<{ reviewThreads: GitHubPullRequestReviewThread[]; truncated: boolean; headSha: string | null; }> { const threads: GitHubPullRequestReviewThread[] = []; let cursor: string | null = null; let truncated = false; let headSha: string | null = null; const pageLimit = options.eventBudget ? 100 : 5; for (let page = 0; page < pageLimit; page += 1) { if (!(options.eventBudget?.canFetch('review_threads') ?? true)) { truncated = true; break; } const data = await githubGraphqlFetch( options.token, query, { owner: options.owner, name: options.repo, number: options.number, after: cursor, }, { signal: options.signal }, ); const parsed = v.parse(githubReviewThreadsGraphqlResponseSchema, data); const pullRequest = parsed.data.repository?.pullRequest; if (!pullRequest) break; const pageHeadSha = pullRequest.headRefOid ?? null; if (headSha && pageHeadSha && pageHeadSha !== headSha) { throw new Error( `Pull request head changed from ${headSha} to ${pageHeadSha} while loading review threads.`, ); } headSha ??= pageHeadSha; for (const thread of pullRequest.reviewThreads.nodes ?? []) { const normalized = await normalizeReviewThread( options.token, thread, options.signal, options.eventBudget, pageHeadSha, ); if (!normalized) { truncated = true; break; } threads.push(normalized); } if (truncated) break; if (!pullRequest.reviewThreads.pageInfo.hasNextPage) break; if (page === pageLimit - 1) { truncated = true; console.warn( `[neondeck] GitHub review thread fetch reached the page cap for ${options.owner}/${options.repo}#${options.number}; results may be truncated.`, ); break; } cursor = pullRequest.reviewThreads.pageInfo.endCursor ?? null; if (!cursor) { truncated = true; break; } } return { reviewThreads: threads, headSha, truncated: truncated || threads.some((thread) => thread.commentsTruncated === true), }; } export async function fetchPullRequestReviewThread(options: { token: string; threadId: string; signal?: AbortSignal; }): Promise { const data = await githubGraphqlFetch( options.token, pullRequestReviewThreadNodeQuery, { threadId: options.threadId }, { signal: options.signal }, ); const parsed = v.parse(githubReviewThreadNodeGraphqlResponseSchema, data); const thread = parsed.data.node; if (!thread) { throw new Error( `GitHub review thread "${options.threadId}" was not found.`, ); } const normalized = await normalizeReviewThread( options.token, thread, options.signal, undefined, thread.pullRequest?.headRefOid ?? null, ); if (!normalized) { throw new Error( `GitHub review thread "${options.threadId}" exceeded its fetch budget.`, ); } return normalized; } async function normalizeReviewThread( token: string, thread: GitHubReviewThreadGraphqlNode, signal?: AbortSignal, eventBudget?: PullRequestEventFetchBudget, expectedHeadSha?: string | null, ): Promise { if ( eventBudget?.admit('review_threads', { id: thread.id, path: thread.path, line: thread.line, isResolved: thread.isResolved, isOutdated: thread.isOutdated, }) === false ) { return undefined; } const comments = await fetchAllReviewThreadComments( token, thread, signal, eventBudget, expectedHeadSha, ); return { id: thread.id, isResolved: thread.isResolved, isOutdated: thread.isOutdated, path: thread.path ?? null, line: thread.line ?? null, originalLine: thread.originalLine ?? null, diffSide: thread.diffSide ?? null, pullRequestRepo: thread.pullRequest?.repository.nameWithOwner ?? null, pullRequestNumber: thread.pullRequest?.number ?? null, commentsTruncated: comments.truncated, comments: comments.items.map((comment) => normalizeReviewThreadComment(comment, thread), ), }; } async function fetchAllReviewThreadComments( token: string, thread: GitHubReviewThreadGraphqlNode, signal?: AbortSignal, eventBudget?: PullRequestEventFetchBudget, expectedHeadSha?: string | null, ) { const comments: GitHubReviewThreadCommentGraphqlNode[] = []; let truncated = false; for (const comment of thread.comments.nodes ?? []) { if (eventBudget?.admit('review_threads', comment) === false) { truncated = true; break; } comments.push(comment); } let cursor = thread.comments.pageInfo.endCursor; let hasNextPage = thread.comments.pageInfo.hasNextPage; const pageLimit = eventBudget ? 100 : 10; for (let page = 0; hasNextPage && page < pageLimit && !truncated;) { page += 1; if (!(eventBudget?.canFetch('review_threads') ?? true)) { truncated = true; break; } if (!cursor) { truncated = true; break; } const data = await githubGraphqlFetch( token, reviewThreadCommentsQuery, { threadId: thread.id, after: cursor, }, { signal }, ); const parsed = v.parse( githubReviewThreadCommentsGraphqlResponseSchema, data, ); const node = parsed.data.node; if (!node?.comments) break; const pageHeadSha = node.pullRequest?.headRefOid ?? null; if (expectedHeadSha && pageHeadSha && pageHeadSha !== expectedHeadSha) { throw new Error( `Pull request head changed from ${expectedHeadSha} to ${pageHeadSha} while loading review thread comments.`, ); } for (const comment of node.comments.nodes ?? []) { if (eventBudget?.admit('review_threads', comment) === false) { truncated = true; break; } comments.push(comment); } if (truncated) break; hasNextPage = node.comments.pageInfo.hasNextPage; if (!hasNextPage) break; cursor = node.comments.pageInfo.endCursor; } truncated = truncated || hasNextPage; return { items: comments, truncated }; } function normalizeReviewThreadComment( comment: GitHubReviewThreadCommentGraphqlNode, thread: Pick, ): GitHubPullRequestReviewThreadComment { return { id: comment.id, databaseId: comment.databaseId ?? null, authorLogin: comment.author?.login ?? null, authorType: comment.author?.__typename ?? null, authorIsBot: comment.author?.__typename === undefined ? undefined : comment.author.__typename === 'Bot', body: comment.body, url: comment.url ?? null, path: comment.path ?? thread.path ?? null, line: comment.line ?? thread.line ?? null, originalLine: comment.originalLine ?? null, diffHunk: comment.diffHunk ?? null, reviewId: comment.pullRequestReview?.databaseId ?? null, createdAt: comment.createdAt, updatedAt: comment.updatedAt, }; }