-
Notifications
You must be signed in to change notification settings - Fork 93
feat: add PR conflict detection with system pins via GitHub App #48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MrgSub
wants to merge
1
commit into
better-auth:main
Choose a base branch
from
MrgSub:feat/pr-conflict-detection-system-pins
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,243 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import crypto from "node:crypto"; | ||
| import { redis } from "@/lib/redis"; | ||
| import { inngest } from "@/lib/inngest"; | ||
| import { getWebhookSecret } from "@/lib/github-app"; | ||
| import { | ||
| upsertInstallation, | ||
| removeInstallation, | ||
| suspendInstallation, | ||
| unsuspendInstallation, | ||
| syncInstallationRepos, | ||
| addInstallationRepos, | ||
| removeInstallationRepos, | ||
| touchRepoWebhook, | ||
| } from "@/lib/github-app-store"; | ||
|
|
||
| // ── Signature Verification ─────────────────────────────────── | ||
|
|
||
| function verifySignature(payload: string, signature: string | null, secret: string): boolean { | ||
| if (!signature) return false; | ||
| const expected = `sha256=${crypto.createHmac("sha256", secret).update(payload).digest("hex")}`; | ||
| try { | ||
| return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature)); | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| // ── Delivery Deduplication ─────────────────────────────────── | ||
|
|
||
| const DEDUPE_TTL_SECONDS = 60 * 60; // 1 hour | ||
|
|
||
| async function isDuplicateDelivery(deliveryId: string): Promise<boolean> { | ||
| const result = await redis.set(`webhook:delivery:${deliveryId}`, "1", { | ||
| nx: true, | ||
| ex: DEDUPE_TTL_SECONDS, | ||
| }); | ||
| return result === null; | ||
| } | ||
|
|
||
| // ── PR Actions We Care About ───────────────────────────────── | ||
|
|
||
| const PR_ACTIONS_EVALUATE = new Set([ | ||
| "opened", | ||
| "reopened", | ||
| "synchronize", | ||
| "edited", | ||
| "ready_for_review", | ||
| ]); | ||
| const PR_ACTIONS_CLOSE = new Set(["closed"]); | ||
|
|
||
| // ── Webhook Payload Types ──────────────────────────────────── | ||
|
|
||
| interface WebhookRepo { | ||
| id: number; | ||
| name: string; | ||
| full_name: string; | ||
| } | ||
|
|
||
| // ── Route Handler ──────────────────────────────────────────── | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| const secret = getWebhookSecret(); | ||
| if (!secret) { | ||
| console.error("[webhook] GitHub App webhook secret not configured"); | ||
| return NextResponse.json({ error: "Webhook secret not configured" }, { status: 500 }); | ||
| } | ||
|
|
||
| // Read raw body for signature verification | ||
| const rawBody = await request.text(); | ||
| const signature = request.headers.get("x-hub-signature-256"); | ||
|
|
||
| if (!verifySignature(rawBody, signature, secret)) { | ||
| return NextResponse.json({ error: "Invalid signature" }, { status: 401 }); | ||
| } | ||
|
|
||
| // Deduplicate | ||
| const deliveryId = request.headers.get("x-github-delivery"); | ||
| if (deliveryId && (await isDuplicateDelivery(deliveryId))) { | ||
| return NextResponse.json({ status: "duplicate", deliveryId }); | ||
| } | ||
|
|
||
| const eventType = request.headers.get("x-github-event"); | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| let payload: any; | ||
| try { | ||
| payload = JSON.parse(rawBody); | ||
| } catch { | ||
| return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); | ||
| } | ||
|
|
||
| // ── Installation lifecycle events ──────────────────────── | ||
| if (eventType === "installation") { | ||
| return handleInstallationEvent(payload); | ||
| } | ||
|
|
||
| if (eventType === "installation_repositories") { | ||
| return handleInstallationRepositoriesEvent(payload); | ||
| } | ||
|
|
||
| // ── Pull request events ────────────────────────────────── | ||
| if (eventType === "pull_request") { | ||
| return handlePullRequestEvent(payload); | ||
| } | ||
|
|
||
| return NextResponse.json({ status: "ignored", event: eventType }); | ||
| } | ||
|
|
||
| // ── Installation Event Handler ─────────────────────────────── | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| async function handleInstallationEvent(payload: any) { | ||
| const { action, installation, repositories } = payload; | ||
| const installationId: number = installation.id; | ||
| const accountLogin: string = installation.account.login; | ||
| const accountType: string = installation.account.type; | ||
| const appSlug: string = installation.app_slug; | ||
|
|
||
| if (action === "created") { | ||
| await upsertInstallation({ | ||
| installationId, | ||
| accountLogin, | ||
| accountType, | ||
| appSlug, | ||
| permissions: installation.permissions, | ||
| events: installation.events, | ||
| }); | ||
|
|
||
| // Sync initial repos | ||
| if (repositories && Array.isArray(repositories)) { | ||
| const repos = (repositories as WebhookRepo[]).map((r) => { | ||
| const [owner, repo] = r.full_name.split("/"); | ||
| return { owner, repo }; | ||
| }); | ||
| await syncInstallationRepos(installationId, repos); | ||
| } | ||
|
|
||
| console.log(`[webhook] Installation created: ${installationId} for ${accountLogin}`); | ||
| return NextResponse.json({ status: "processed", action: "installation.created" }); | ||
| } | ||
|
|
||
| if (action === "deleted") { | ||
| await removeInstallation(installationId); | ||
| console.log(`[webhook] Installation removed: ${installationId} for ${accountLogin}`); | ||
| return NextResponse.json({ status: "processed", action: "installation.deleted" }); | ||
| } | ||
|
|
||
| if (action === "suspend") { | ||
| await suspendInstallation(installationId); | ||
| console.log(`[webhook] Installation suspended: ${installationId}`); | ||
| return NextResponse.json({ status: "processed", action: "installation.suspend" }); | ||
| } | ||
|
|
||
| if (action === "unsuspend") { | ||
| await unsuspendInstallation(installationId); | ||
| console.log(`[webhook] Installation unsuspended: ${installationId}`); | ||
| return NextResponse.json({ status: "processed", action: "installation.unsuspend" }); | ||
| } | ||
|
|
||
| return NextResponse.json({ status: "ignored", action: `installation.${action}` }); | ||
| } | ||
|
|
||
| // ── Installation Repositories Event Handler ────────────────── | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| async function handleInstallationRepositoriesEvent(payload: any) { | ||
| const { action, installation, repositories_added, repositories_removed } = payload; | ||
| const installationId: number = installation.id; | ||
|
|
||
| if (action === "added" && repositories_added) { | ||
| const repos = (repositories_added as WebhookRepo[]).map((r) => { | ||
| const [owner, repo] = r.full_name.split("/"); | ||
| return { owner, repo }; | ||
| }); | ||
| await addInstallationRepos(installationId, repos); | ||
| console.log(`[webhook] Repos added to installation ${installationId}: ${repos.map((r) => `${r.owner}/${r.repo}`).join(", ")}`); | ||
| return NextResponse.json({ status: "processed", action: "repos.added", count: repos.length }); | ||
| } | ||
|
|
||
| if (action === "removed" && repositories_removed) { | ||
| const repos = (repositories_removed as WebhookRepo[]).map((r) => { | ||
| const [owner, repo] = r.full_name.split("/"); | ||
| return { owner, repo }; | ||
| }); | ||
| await removeInstallationRepos(installationId, repos); | ||
| console.log(`[webhook] Repos removed from installation ${installationId}: ${repos.map((r) => `${r.owner}/${r.repo}`).join(", ")}`); | ||
| return NextResponse.json({ status: "processed", action: "repos.removed", count: repos.length }); | ||
| } | ||
|
|
||
| return NextResponse.json({ status: "ignored", action: `repos.${action}` }); | ||
| } | ||
|
|
||
| // ── Pull Request Event Handler ─────────────────────────────── | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| async function handlePullRequestEvent(payload: any) { | ||
| const { action, number: pullNumber, pull_request: pr, repository: repo, installation } = payload; | ||
| const owner: string = repo.owner.login; | ||
| const repoName: string = repo.name; | ||
| const installationId: number | undefined = installation?.id; | ||
|
|
||
| // Track webhook activity | ||
| if (installationId) { | ||
| touchRepoWebhook(installationId, owner, repoName).catch((err) => { | ||
| console.error("[webhook] Failed to touch repo webhook timestamp:", err); | ||
| }); | ||
| } | ||
|
|
||
| if (PR_ACTIONS_CLOSE.has(action)) { | ||
| await inngest.send({ | ||
| name: "app/pr.conflict.clear", | ||
| data: { | ||
| owner, | ||
| repo: repoName, | ||
| pullNumber, | ||
| reason: pr.merged ? "merged" : "closed", | ||
| }, | ||
| }); | ||
| return NextResponse.json({ status: "processed", action: "clear", pullNumber }); | ||
| } | ||
|
|
||
| if (PR_ACTIONS_EVALUATE.has(action)) { | ||
| await inngest.send({ | ||
| name: "app/pr.conflict.evaluate", | ||
| data: { | ||
| owner, | ||
| repo: repoName, | ||
| pullNumber, | ||
| installationId: installationId ?? null, | ||
| title: pr.title, | ||
| url: pr.html_url, | ||
| headRef: pr.head.ref, | ||
| baseRef: pr.base.ref, | ||
| webhookAction: action, | ||
| source: "github_app_webhook", | ||
| }, | ||
| }); | ||
| return NextResponse.json({ status: "processed", action: "evaluate", pullNumber }); | ||
| } | ||
|
|
||
| return NextResponse.json({ status: "ignored", action }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,7 @@ | ||
| import { serve } from "inngest/next"; | ||
| import { inngest, embedContent } from "@/lib/inngest"; | ||
| import { inngest, embedContent, evaluatePRConflict, clearPRConflict, pollConflicts } from "@/lib/inngest"; | ||
|
|
||
| export const { GET, POST, PUT } = serve({ | ||
| client: inngest, | ||
| functions: [embedContent], | ||
| functions: [embedContent, evaluatePRConflict, clearPRConflict, pollConflicts], | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yrs