-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathroute.ts
More file actions
308 lines (257 loc) · 12.5 KB
/
route.ts
File metadata and controls
308 lines (257 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
'use server';
import { NextRequest } from "next/server";
import { App, Octokit } from "octokit";
import { WebhookEventDefinition} from "@octokit/webhooks/types";
import { Gitlab } from "@gitbeaker/rest";
import { env } from "@sourcebot/shared";
import { processGitHubPullRequest, processGitLabMergeRequest } from "@/features/agents/review-agent/app";
import { throttling, type ThrottlingOptions } from "@octokit/plugin-throttling";
import fs from "fs";
import { GitHubPullRequest, GitLabMergeRequestPayload, gitLabMergeRequestPayloadSchema, gitLabNotePayloadSchema } from "@/features/agents/review-agent/types";
import { createLogger } from "@sourcebot/shared";
const logger = createLogger('webhook');
const DEFAULT_GITHUB_API_BASE_URL = "https://api.github.com";
type GitHubAppBaseOptions = Omit<ConstructorParameters<typeof App>[0], "Octokit"> & { throttle: ThrottlingOptions };
let githubAppBaseOptions: GitHubAppBaseOptions | undefined;
const githubAppCache = new Map<string, App>();
if (env.GITHUB_REVIEW_AGENT_APP_ID && env.GITHUB_REVIEW_AGENT_APP_WEBHOOK_SECRET && env.GITHUB_REVIEW_AGENT_APP_PRIVATE_KEY_PATH) {
try {
const privateKey = fs.readFileSync(env.GITHUB_REVIEW_AGENT_APP_PRIVATE_KEY_PATH, "utf8");
githubAppBaseOptions = {
appId: env.GITHUB_REVIEW_AGENT_APP_ID,
privateKey,
webhooks: {
secret: env.GITHUB_REVIEW_AGENT_APP_WEBHOOK_SECRET,
},
throttle: {
enabled: true,
onRateLimit: (retryAfter, _options, _octokit, retryCount) => {
if (retryCount > 3) {
logger.warn(`Rate limit exceeded: ${retryAfter} seconds`);
return false;
}
return true;
},
onSecondaryRateLimit: (_retryAfter, options) => {
// no retries on secondary rate limits
logger.warn(`SecondaryRateLimit detected for ${options.method} ${options.url}`);
}
},
};
} catch (error) {
logger.error(`Error initializing GitHub app: ${error}`);
}
}
const normalizeGithubApiBaseUrl = (baseUrl?: string) => {
if (!baseUrl) {
return DEFAULT_GITHUB_API_BASE_URL;
}
return baseUrl.replace(/\/+$/, "");
};
const resolveGithubApiBaseUrl = (headers: Record<string, string>) => {
const enterpriseHost = headers["x-github-enterprise-host"];
if (enterpriseHost) {
return normalizeGithubApiBaseUrl(`https://${enterpriseHost}/api/v3`);
}
return DEFAULT_GITHUB_API_BASE_URL;
};
const getGithubAppForBaseUrl = (baseUrl: string) => {
if (!githubAppBaseOptions) {
return undefined;
}
const normalizedBaseUrl = normalizeGithubApiBaseUrl(baseUrl);
const cachedApp = githubAppCache.get(normalizedBaseUrl);
if (cachedApp) {
return cachedApp;
}
const OctokitWithBaseUrl = Octokit.plugin(throttling).defaults({ baseUrl: normalizedBaseUrl });
const app = new App({
...githubAppBaseOptions,
Octokit: OctokitWithBaseUrl,
});
githubAppCache.set(normalizedBaseUrl, app);
return app;
};
function isPullRequestEvent(eventHeader: string, payload: unknown): payload is WebhookEventDefinition<"pull-request-opened"> | WebhookEventDefinition<"pull-request-synchronize"> {
return eventHeader === "pull_request" && typeof payload === "object" && payload !== null && "action" in payload && typeof payload.action === "string" && (payload.action === "opened" || payload.action === "synchronize");
}
function isIssueCommentEvent(eventHeader: string, payload: unknown): payload is WebhookEventDefinition<"issue-comment-created"> {
return eventHeader === "issue_comment" && typeof payload === "object" && payload !== null && "action" in payload && typeof payload.action === "string" && payload.action === "created";
}
function isGitLabMergeRequestEvent(eventHeader: string, payload: unknown): boolean {
return (
eventHeader === "Merge Request Hook" &&
typeof payload === "object" &&
payload !== null &&
"object_attributes" in payload &&
typeof (payload as Record<string, unknown> & { object_attributes: { action?: unknown } }).object_attributes?.action === "string" &&
["open", "update", "reopen"].includes((payload as Record<string, unknown> & { object_attributes: { action: string } }).object_attributes.action)
);
}
function isGitLabNoteEvent(eventHeader: string, payload: unknown): boolean {
return (
eventHeader === "Note Hook" &&
typeof payload === "object" &&
payload !== null &&
"object_attributes" in payload &&
(payload as Record<string, unknown> & { object_attributes: { noteable_type?: unknown } }).object_attributes?.noteable_type === "MergeRequest"
);
}
let gitlabClient: InstanceType<typeof Gitlab> | undefined;
if (env.GITLAB_REVIEW_AGENT_TOKEN) {
try {
gitlabClient = new Gitlab({
host: `https://${env.GITLAB_REVIEW_AGENT_HOST}`,
token: env.GITLAB_REVIEW_AGENT_TOKEN,
});
} catch (error) {
logger.error(`Error initializing GitLab client: ${error}`);
}
}
const ACK_TIMEOUT_MS = 1500;
const ackWithTimeout = (promise: Promise<unknown>, label: string): Promise<void> => {
const timeout = new Promise<void>(resolve => setTimeout(resolve, ACK_TIMEOUT_MS));
return Promise.race([promise, timeout]).then(
() => { /* success or timeout — proceed */ },
(error) => { logger.warn(`${label}: ${error}`); },
);
};
export const POST = async (request: NextRequest) => {
const body = await request.json();
const headers = Object.fromEntries(Array.from(request.headers.entries(), ([key, value]) => [key.toLowerCase(), value]));
const githubEvent = headers['x-github-event'];
if (githubEvent) {
logger.info('GitHub event received:', githubEvent);
const githubApiBaseUrl = resolveGithubApiBaseUrl(headers);
logger.debug('Using GitHub API base URL for event', { githubApiBaseUrl });
const githubApp = getGithubAppForBaseUrl(githubApiBaseUrl);
if (!githubApp) {
logger.warn('Received GitHub webhook event but GitHub app env vars are not set');
return Response.json({ status: 'ok' });
}
if (isPullRequestEvent(githubEvent, body)) {
if (env.REVIEW_AGENT_AUTO_REVIEW_ENABLED === "false") {
logger.info('Review agent auto review (REVIEW_AGENT_AUTO_REVIEW_ENABLED) is disabled, skipping');
return Response.json({ status: 'ok' });
}
if (!body.installation) {
logger.error('Received github pull request event but installation is not present');
return Response.json({ status: 'ok' });
}
const installationId = body.installation.id;
const octokit = await githubApp.getInstallationOctokit(installationId);
const pullRequest = body.pull_request as GitHubPullRequest;
await processGitHubPullRequest(octokit, pullRequest);
}
if (isIssueCommentEvent(githubEvent, body)) {
const comment = body.comment.body;
if (!comment) {
logger.warn('Received issue comment event but comment body is empty');
return Response.json({ status: 'ok' });
}
if (comment === `/${env.REVIEW_AGENT_REVIEW_COMMAND}`) {
logger.info('Review agent review command received, processing');
if (!body.installation) {
logger.error('Received github issue comment event but installation is not present');
return Response.json({ status: 'ok' });
}
const pullRequestNumber = body.issue.number;
const repositoryName = body.repository.name;
const owner = body.repository.owner.login;
const octokit = await githubApp.getInstallationOctokit(body.installation.id);
await ackWithTimeout(
octokit.rest.reactions.createForIssueComment({
owner,
repo: repositoryName,
comment_id: body.comment.id,
content: env.REVIEW_AGENT_ACK_REACTION as "-1" | "+1" | "laugh" | "confused" | "heart" | "hooray" | "rocket" | "eyes",
}),
'Failed to add acknowledgment reaction to GitHub comment',
);
const { data: pullRequest } = await octokit.rest.pulls.get({
owner,
repo: repositoryName,
pull_number: pullRequestNumber,
});
await processGitHubPullRequest(octokit, pullRequest);
}
}
}
const gitlabEvent = headers['x-gitlab-event'];
if (gitlabEvent) {
logger.info('GitLab event received:', gitlabEvent);
const token = headers['x-gitlab-token'];
if (!env.GITLAB_REVIEW_AGENT_WEBHOOK_SECRET || token !== env.GITLAB_REVIEW_AGENT_WEBHOOK_SECRET) {
logger.warn('GitLab webhook token is invalid or GITLAB_REVIEW_AGENT_WEBHOOK_SECRET is not set');
return Response.json({ status: 'ok' });
}
if (!gitlabClient) {
logger.warn('Received GitLab webhook event but GITLAB_REVIEW_AGENT_TOKEN is not set');
return Response.json({ status: 'ok' });
}
if (isGitLabMergeRequestEvent(gitlabEvent, body)) {
if (env.REVIEW_AGENT_AUTO_REVIEW_ENABLED === "false") {
logger.info('Review agent auto review (REVIEW_AGENT_AUTO_REVIEW_ENABLED) is disabled, skipping');
return Response.json({ status: 'ok' });
}
const parsed = gitLabMergeRequestPayloadSchema.safeParse(body);
if (!parsed.success) {
logger.warn(`GitLab MR webhook payload failed validation: ${parsed.error.message}`);
return Response.json({ status: 'ok' });
}
try {
await processGitLabMergeRequest(
gitlabClient,
parsed.data.project.id,
parsed.data,
env.GITLAB_REVIEW_AGENT_HOST,
);
} catch (error) {
logger.error(`Error in processGitLabMergeRequest for project ${parsed.data.project.id} (${gitlabEvent}):`, error);
}
}
if (isGitLabNoteEvent(gitlabEvent, body)) {
const parsed = gitLabNotePayloadSchema.safeParse(body);
if (!parsed.success) {
logger.warn(`GitLab Note webhook payload failed validation: ${parsed.error.message}`);
return Response.json({ status: 'ok' });
}
const noteBody = parsed.data.object_attributes.note;
if (noteBody === `/${env.REVIEW_AGENT_REVIEW_COMMAND}`) {
logger.info('Review agent review command received on GitLab MR, processing');
await ackWithTimeout(
gitlabClient.MergeRequestNoteAwardEmojis.award(
parsed.data.project.id,
parsed.data.merge_request.iid,
parsed.data.object_attributes.id,
env.REVIEW_AGENT_ACK_REACTION,
),
'Failed to add acknowledgment emoji to GitLab note',
);
const mrPayload: GitLabMergeRequestPayload = {
object_kind: "merge_request",
object_attributes: {
iid: parsed.data.merge_request.iid,
title: parsed.data.merge_request.title,
description: parsed.data.merge_request.description,
action: "update",
last_commit: parsed.data.merge_request.last_commit,
diff_refs: parsed.data.merge_request.diff_refs,
},
project: parsed.data.project,
};
try {
await processGitLabMergeRequest(
gitlabClient,
parsed.data.project.id,
mrPayload,
env.GITLAB_REVIEW_AGENT_HOST,
);
} catch (error) {
logger.error(`Error in processGitLabMergeRequest for project ${parsed.data.project.id} (${gitlabEvent}):`, error);
}
}
}
}
return Response.json({ status: 'ok' });
}