diff --git a/README.md b/README.md index 8022836..1682d62 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ GitHub Actions bot that reviews pull requests with an AI reviewer, leaves inline - If the reviewer detects clearly malicious code, the bot comments with the reason and closes the pull request. - Posts inline comments only on valid added diff lines. - Approves clean pull requests. +- Retries transient OpenAI and GitHub API request failures up to 5 times before giving up. - If `AUTO_MERGE=true`, merges only after: - the AI reviewer says the PR is safe, - GitHub reports the PR as mergeable, diff --git a/src/actions/runReview.ts b/src/actions/runReview.ts index 57bc135..67ec0d9 100644 --- a/src/actions/runReview.ts +++ b/src/actions/runReview.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import { config } from "../config.js"; import { createGitHubClient } from "../github/client.js"; import { logger } from "../logger.js"; +import { withRetry } from "../retry.js"; import { processLenientCheckComment, processPullRequest, @@ -73,11 +74,13 @@ async function main(): Promise { if (eventName === "pull_request_target") { const prPayload = payload as PullRequestPayload; if (prPayload.action === "opened") { - await octokit.rest.issues.createComment({ - owner: prPayload.repository.owner.login, - repo: prPayload.repository.name, - issue_number: prPayload.pull_request.number, - body: "Automated review has started. I am checking this pull request now." + await withRetry("github.issues.createComment.started", async () => { + return octokit.rest.issues.createComment({ + owner: prPayload.repository.owner.login, + repo: prPayload.repository.name, + issue_number: prPayload.pull_request.number, + body: "Automated review has started. I am checking this pull request now." + }); }); } diff --git a/src/retry.ts b/src/retry.ts new file mode 100644 index 0000000..85f37e5 --- /dev/null +++ b/src/retry.ts @@ -0,0 +1,47 @@ +import { logger } from "./logger.js"; + +const MAX_ATTEMPTS = 5; +const BASE_DELAY_MS = 1_000; + +export async function withRetry( + label: string, + operation: () => Promise, + options?: { + maxAttempts?: number; + baseDelayMs?: number; + } +): Promise { + const maxAttempts = options?.maxAttempts ?? MAX_ATTEMPTS; + const baseDelayMs = options?.baseDelayMs ?? BASE_DELAY_MS; + let lastError: unknown; + + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + try { + return await operation(); + } catch (error) { + lastError = error; + + logger.warn( + { + error, + label, + attempt, + maxAttempts + }, + "Request failed." + ); + + if (attempt === maxAttempts) { + break; + } + + await delay(baseDelayMs * attempt); + } + } + + throw lastError; +} + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/src/review/openaiReviewer.ts b/src/review/openaiReviewer.ts index 3a7b54c..79a7e59 100644 --- a/src/review/openaiReviewer.ts +++ b/src/review/openaiReviewer.ts @@ -1,6 +1,7 @@ import { OpenAI } from "openai"; import { z } from "zod"; import { config } from "../config.js"; +import { withRetry } from "../retry.js"; import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js"; const reviewDecisionSchema = z.object({ @@ -31,62 +32,64 @@ export class OpenAiReviewer { files: PullRequestFile[]; mode: ReviewMode; }): Promise { - const response = await this.client.responses.create({ - model: config.openAiModel, - temperature: 0.1, - ...(config.openAiReasoningEffort ? { reasoning: { effort: config.openAiReasoningEffort } } : {}), - text: { - format: { - name: "pull_request_review", - type: "json_schema", - strict: true, - schema: { - type: "object", - additionalProperties: false, - required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"], - properties: { - safeToMerge: { type: "boolean" }, - shouldClosePullRequest: { type: "boolean" }, - closeReason: { type: "string" }, - summary: { type: "string" }, - findings: { - type: "array", - items: { - type: "object", - additionalProperties: false, - required: ["path", "line", "severity", "title", "body"], - properties: { - path: { type: "string" }, - line: { type: "integer", minimum: 1 }, - severity: { type: "string", enum: ["blocking", "suggestion"] }, - title: { type: "string" }, - body: { type: "string" } + const response = await withRetry("openai.responses.create", async () => { + return this.client.responses.create({ + model: config.openAiModel, + temperature: 0.1, + ...(config.openAiReasoningEffort ? { reasoning: { effort: config.openAiReasoningEffort } } : {}), + text: { + format: { + name: "pull_request_review", + type: "json_schema", + strict: true, + schema: { + type: "object", + additionalProperties: false, + required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"], + properties: { + safeToMerge: { type: "boolean" }, + shouldClosePullRequest: { type: "boolean" }, + closeReason: { type: "string" }, + summary: { type: "string" }, + findings: { + type: "array", + items: { + type: "object", + additionalProperties: false, + required: ["path", "line", "severity", "title", "body"], + properties: { + path: { type: "string" }, + line: { type: "integer", minimum: 1 }, + severity: { type: "string", enum: ["blocking", "suggestion"] }, + title: { type: "string" }, + body: { type: "string" } + } } } } } } - } - }, - instructions: buildSystemPrompt(input.mode), - input: [ - { - role: "user", - content: JSON.stringify({ - pullRequest: { - title: input.title, - body: input.body ?? "" - }, - files: input.files.map((file) => ({ - path: file.filename, - status: file.status, - additions: file.additions, - deletions: file.deletions, - patch: file.patch ?? "" - })) - }) - } - ] + }, + instructions: buildSystemPrompt(input.mode), + input: [ + { + role: "user", + content: JSON.stringify({ + pullRequest: { + title: input.title, + body: input.body ?? "" + }, + files: input.files.map((file) => ({ + path: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + patch: file.patch ?? "" + })) + }) + } + ] + }); }); const raw = response.output_text; diff --git a/src/review/processor.ts b/src/review/processor.ts index 3a55c39..b4d2df8 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -3,6 +3,7 @@ import { config } from "../config.js"; import { requiredChecksAreGreen } from "../github/checks.js"; import { collectValidNewLines, toDiffPosition } from "../github/diff.js"; import { logger } from "../logger.js"; +import { withRetry } from "../retry.js"; import type { PullRequestFile, PullRequestRef, ReviewDecision, ReviewFinding, ReviewMode } from "../types.js"; import { formatReviewBody } from "./format.js"; import { OpenAiReviewer } from "./openaiReviewer.js"; @@ -188,11 +189,13 @@ export async function processLenientCheckComment( "Processing lenient check comment command." ); - await octokit.rest.issues.createComment({ - owner: params.owner, - repo: params.repo, - issue_number: params.pullNumber, - body: `Lenient check requested by @${params.commenterLogin}. Re-running the review with runtime and security focus only.` + await withRetry("github.issues.createComment.lenientRequested", async () => { + return octokit.rest.issues.createComment({ + owner: params.owner, + repo: params.repo, + issue_number: params.pullNumber, + body: `Lenient check requested by @${params.commenterLogin}. Re-running the review with runtime and security focus only.` + }); }); await processPullRequest( @@ -234,11 +237,13 @@ async function maybeMergePullRequest( }); if (!approvedByOwner) { - await octokit.rest.issues.createComment({ - owner, - repo, - issue_number: pullNumber, - body: `Lenient check passed, but this PR will not be merged until @${config.lenientApprovalUser} approves the current head commit.` + await withRetry("github.issues.createComment.awaitLenientApproval", async () => { + return octokit.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body: `Lenient check passed, but this PR will not be merged until @${config.lenientApprovalUser} approves the current head commit.` + }); }); logger.info({ owner, repo, pullNumber, reviewer: config.lenientApprovalUser }, "Waiting for lenient approval before merging."); return; @@ -247,11 +252,13 @@ async function maybeMergePullRequest( const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber); if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") { - await octokit.rest.issues.createComment({ - owner, - repo, - issue_number: pullNumber, - body: `Automated review approved this PR, but it was not merged because GitHub reports mergeable=${mergeablePullRequest.mergeable} and mergeable_state=${mergeablePullRequest.mergeable_state}.` + await withRetry("github.issues.createComment.notMergeable", async () => { + return octokit.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body: `Automated review approved this PR, but it was not merged because GitHub reports mergeable=${mergeablePullRequest.mergeable} and mergeable_state=${mergeablePullRequest.mergeable_state}.` + }); }); return; } @@ -263,22 +270,26 @@ async function maybeMergePullRequest( ref: params.headSha }); if (!checks.ok) { - await octokit.rest.issues.createComment({ - owner, - repo, - issue_number: pullNumber, - body: `Automated review approved this PR, but it was not merged because required checks are not green. ${checks.reason ?? ""}`.trim() + await withRetry("github.issues.createComment.requiredChecks", async () => { + return octokit.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body: `Automated review approved this PR, but it was not merged because required checks are not green. ${checks.reason ?? ""}`.trim() + }); }); return; } } - await octokit.rest.pulls.merge({ - owner, - repo, - pull_number: pullNumber, - merge_method: config.mergeMethod, - commit_title: `${params.title} (#${pullNumber})` + await withRetry("github.pulls.merge", async () => { + return octokit.rest.pulls.merge({ + owner, + repo, + pull_number: pullNumber, + merge_method: config.mergeMethod, + commit_title: `${params.title} (#${pullNumber})` + }); }); } @@ -380,14 +391,16 @@ async function submitReview( const event: "APPROVE" | "REQUEST_CHANGES" = params.decision.safeToMerge && !hasBlockingFinding ? "APPROVE" : "REQUEST_CHANGES"; - await octokit.rest.pulls.createReview({ - owner: params.owner, - repo: params.repo, - pull_number: params.pullNumber, - commit_id: params.commitId, - event, - body: formatReviewBody(params.decision, unpostedFindings, params.mode), - comments + await withRetry("github.pulls.createReview", async () => { + return octokit.rest.pulls.createReview({ + owner: params.owner, + repo: params.repo, + pull_number: params.pullNumber, + commit_id: params.commitId, + event, + body: formatReviewBody(params.decision, unpostedFindings, params.mode), + comments + }); }); } @@ -406,24 +419,26 @@ async function upsertReviewCheckRun( const conclusion = params.decision.shouldClosePullRequest || hasBlockingFinding || !params.decision.safeToMerge ? "action_required" : "success"; - await octokit.rest.checks.create({ - owner: params.owner, - repo: params.repo, - name: CHECK_RUN_NAME, - head_sha: params.headSha, - status: "completed", - conclusion, - output: { - title: params.decision.shouldClosePullRequest - ? "Malicious code detected" - : params.mode === "lenient" - ? "Lenient review completed" - : "Strict review completed", - summary: params.decision.shouldClosePullRequest - ? `${params.decision.summary}\n\nClose reason: ${params.decision.closeReason}` - : params.decision.summary - }, - details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}` + await withRetry("github.checks.create", async () => { + return octokit.rest.checks.create({ + owner: params.owner, + repo: params.repo, + name: CHECK_RUN_NAME, + head_sha: params.headSha, + status: "completed", + conclusion, + output: { + title: params.decision.shouldClosePullRequest + ? "Malicious code detected" + : params.mode === "lenient" + ? "Lenient review completed" + : "Strict review completed", + summary: params.decision.shouldClosePullRequest + ? `${params.decision.summary}\n\nClose reason: ${params.decision.closeReason}` + : params.decision.summary + }, + details_url: `https://github.com/${params.owner}/${params.repo}/pull/${params.pullNumber}` + }); }); } @@ -440,18 +455,22 @@ async function closeMaliciousPullRequest( reason: string; } ): Promise { - await octokit.rest.issues.createComment({ - owner: params.owner, - repo: params.repo, - issue_number: params.pullNumber, - body: `This PR was automatically closed because the review detected clearly malicious code.\n\nReason: ${params.reason}` + await withRetry("github.issues.createComment.closeMalicious", async () => { + return octokit.rest.issues.createComment({ + owner: params.owner, + repo: params.repo, + issue_number: params.pullNumber, + body: `This PR was automatically closed because the review detected clearly malicious code.\n\nReason: ${params.reason}` + }); }); - await octokit.rest.pulls.update({ - owner: params.owner, - repo: params.repo, - pull_number: params.pullNumber, - state: "closed" + await withRetry("github.pulls.update.closeMalicious", async () => { + return octokit.rest.pulls.update({ + owner: params.owner, + repo: params.repo, + pull_number: params.pullNumber, + state: "closed" + }); }); }