-
Notifications
You must be signed in to change notification settings - Fork 362
Expand file tree
/
Copy pathapi.ts
More file actions
135 lines (118 loc) · 4.66 KB
/
Copy pathapi.ts
File metadata and controls
135 lines (118 loc) · 4.66 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
import { createBullBoard } from '@bull-board/api';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter.js';
import { ExpressAdapter } from '@bull-board/express';
import { Octokit } from '@octokit/rest';
import * as Sentry from "@sentry/node";
import { PrismaClient, RepoIndexingJobType } from '@sourcebot/db';
import { createLogger, env, JOB_PRIORITIES } from '@sourcebot/shared';
import express, { NextFunction, Request, Response } from 'express';
import 'express-async-errors';
import * as http from "http";
import z from 'zod';
import { SINGLE_TENANT_ORG_ID } from './constants.js';
import { isGitHubRateLimitError, isNotFound } from './errors.js';
import { PromClient } from './promClient.js';
import { createGitHubRepoRecord } from './repoCompileUtils.js';
import type { JobManager } from './types.js';
const logger = createLogger('api');
const workerApiUrl = new URL(env.WORKER_API_URL);
const PORT = Number(workerApiUrl.port) || (workerApiUrl.protocol === "https:" ? 443 : 80);
export class Api {
private server: http.Server;
constructor(
promClient: PromClient,
private prisma: PrismaClient,
private jobManager: JobManager,
) {
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const bullBoardAdapter = new ExpressAdapter();
bullBoardAdapter.setBasePath('/admin/queues');
createBullBoard({
queues: jobManager.getQueues().map(queue => new BullMQAdapter(queue, { readOnlyMode: true })),
serverAdapter: bullBoardAdapter,
});
app.use('/admin/queues', bullBoardAdapter.getRouter());
// Prometheus metrics endpoint
app.use('/metrics', async (_req: Request, res: Response) => {
res.set('Content-Type', promClient.registry.contentType);
const metrics = await promClient.registry.metrics();
res.end(metrics);
});
app.post(`/api/experimental/add-github-repo`, this.experimental_addGithubRepo.bind(this));
app.use((error: unknown, _req: Request, _res: Response, next: NextFunction) => {
Sentry.captureException(error);
next(error);
});
this.server = app.listen(PORT, () => {
logger.debug(`API server is running on port ${PORT}`);
logger.debug(`Bull Board is available at ${workerApiUrl.origin}/admin/queues`);
});
}
private async experimental_addGithubRepo(req: Request, res: Response) {
const schema = z.object({
owner: z.string(),
repo: z.string(),
}).strict();
const parsed = schema.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: parsed.error.message });
return;
}
const octokit = new Octokit({
auth: env.EXPERIMENT_ASK_GH_GITHUB_TOKEN,
});
let response;
try {
response = await octokit.rest.repos.get({
owner: parsed.data.owner,
repo: parsed.data.repo,
});
} catch (error) {
if (isNotFound(error)) {
res.status(404).json({ error: 'Repository not found on GitHub' });
return;
}
if (isGitHubRateLimitError(error)) {
logger.warn(`GitHub API rate limit exceeded while adding ${parsed.data.owner}/${parsed.data.repo}`);
res.status(429).json({ error: 'GitHub API rate limit exceeded' });
return;
}
throw error;
}
const record = createGitHubRepoRecord({
repo: response.data,
hostUrl: 'https://github.com',
isAutoCleanupDisabled: true,
});
const repo = await this.prisma.repo.upsert({
where: {
external_id_external_codeHostUrl_orgId: {
external_id: record.external_id,
external_codeHostUrl: record.external_codeHostUrl,
orgId: SINGLE_TENANT_ORG_ID,
}
},
update: record,
create: record,
});
const jobId = await this.jobManager.trigger(
'repo-index',
{
repoId: repo.id,
type: RepoIndexingJobType.INDEX,
},
{ priority: JOB_PRIORITIES.INTERACTIVE },
);
res.status(200).json({ jobId, repoId: repo.id });
}
public async dispose() {
return new Promise<void>((resolve, reject) => {
this.server.close((err) => {
if (err) reject(err);
else resolve(undefined);
});
});
}
}