blob: 97df61f15e405290bc4c19fb1e5121210e50ea1a [file] [log] [blame]
giod0026612025-05-08 13:00:36 +00001import { PrismaClient } from "@prisma/client";
2import express from "express";
gioa71316d2025-05-24 09:41:36 +04003import fs from "node:fs";
giod0026612025-05-08 13:00:36 +00004import { env } from "node:process";
5import axios from "axios";
gioc31bf142025-06-16 07:48:20 +00006import { GithubClient } from "./github.js";
gioe085d5b2025-07-08 07:51:36 +00007import { AppManager, DeployResponse } from "./app_manager.js";
gio7d813702025-05-08 18:29:52 +00008import { z } from "zod";
gio78a22882025-07-01 18:56:01 +00009import { ProjectMonitor, WorkerSchema, LogItem } from "./project_monitor.js";
gioa71316d2025-05-24 09:41:36 +040010import tmp from "tmp";
gioc31bf142025-06-16 07:48:20 +000011import { NodeJSAnalyzer } from "./lib/nodejs.js";
gioa71316d2025-05-24 09:41:36 +040012import shell from "shelljs";
gioc31bf142025-06-16 07:48:20 +000013import { RealFileSystem } from "./lib/fs.js";
gioa71316d2025-05-24 09:41:36 +040014import path from "node:path";
gio9b7421a2025-06-18 12:31:13 +000015import {
16 Env,
17 generateDodoConfig,
18 ConfigSchema,
gio56e9f472025-07-07 03:33:38 +000019 Config,
gio9b7421a2025-06-18 12:31:13 +000020 ConfigWithInput,
21 configToGraph,
22 Network,
23 GithubRepository,
gio8a5f12f2025-07-05 07:02:31 +000024 Graph,
gio9b7421a2025-06-18 12:31:13 +000025} from "config";
gio78a22882025-07-01 18:56:01 +000026import { Instant, DateTimeFormatter, ZoneId } from "@js-joda/core";
gio40c0c992025-07-02 13:18:05 +000027import LogStore from "./log.js";
gio785c9882025-07-07 16:40:25 +000028import { GraphOrConfigSchema, GraphSchema, GraphConfigOrDraft, AgentAccess } from "config/dist/graph.js";
gioa71316d2025-05-24 09:41:36 +040029
30async function generateKey(root: string): Promise<[string, string]> {
31 const privKeyPath = path.join(root, "key");
32 const pubKeyPath = path.join(root, "key.pub");
33 if (shell.exec(`ssh-keygen -t ed25519 -f ${privKeyPath} -N ""`).code !== 0) {
34 throw new Error("Failed to generate SSH key pair");
35 }
36 const publicKey = await fs.promises.readFile(pubKeyPath, "utf8");
37 const privateKey = await fs.promises.readFile(privKeyPath, "utf8");
38 return [publicKey, privateKey];
39}
giod0026612025-05-08 13:00:36 +000040
41const db = new PrismaClient();
gio40c0c992025-07-02 13:18:05 +000042const logStore = new LogStore(db);
gio3ed59592025-05-14 16:51:09 +000043const appManager = new AppManager();
giod0026612025-05-08 13:00:36 +000044
gioa1efbad2025-05-21 07:16:45 +000045const projectMonitors = new Map<number, ProjectMonitor>();
gio7d813702025-05-08 18:29:52 +000046
gio10ff1342025-07-05 10:22:15 +000047function parseGraph(data: string | null | undefined) {
48 if (data == null) {
49 return null;
50 }
51 return GraphSchema.safeParse(JSON.parse(data));
52}
53
giod0026612025-05-08 13:00:36 +000054const handleProjectCreate: express.Handler = async (req, resp) => {
55 try {
gioa71316d2025-05-24 09:41:36 +040056 const tmpDir = tmp.dirSync().name;
57 const [publicKey, privateKey] = await generateKey(tmpDir);
giod0026612025-05-08 13:00:36 +000058 const { id } = await db.project.create({
59 data: {
gio09fcab52025-05-12 14:05:07 +000060 userId: resp.locals.userId,
giod0026612025-05-08 13:00:36 +000061 name: req.body.name,
gioa71316d2025-05-24 09:41:36 +040062 deployKey: privateKey,
63 deployKeyPublic: publicKey,
giod0026612025-05-08 13:00:36 +000064 },
65 });
66 resp.status(200);
67 resp.header("Content-Type", "application/json");
68 resp.write(
69 JSON.stringify({
gio74ab7852025-05-13 13:19:31 +000070 id: id.toString(),
giod0026612025-05-08 13:00:36 +000071 }),
72 );
73 } catch (e) {
74 console.log(e);
75 resp.status(500);
76 } finally {
77 resp.end();
78 }
79};
80
81const handleProjectAll: express.Handler = async (req, resp) => {
82 try {
83 const r = await db.project.findMany({
84 where: {
gio09fcab52025-05-12 14:05:07 +000085 userId: resp.locals.userId,
giod0026612025-05-08 13:00:36 +000086 },
87 });
88 resp.status(200);
89 resp.header("Content-Type", "application/json");
90 resp.write(
91 JSON.stringify(
92 r.map((p) => ({
93 id: p.id.toString(),
94 name: p.name,
95 })),
96 ),
97 );
98 } catch (e) {
99 console.log(e);
100 resp.status(500);
101 } finally {
102 resp.end();
103 }
104};
105
gio8a5f12f2025-07-05 07:02:31 +0000106async function getState(projectId: number, userId: string, state: "deploy" | "draft"): Promise<Graph | null> {
107 const r = await db.project.findUnique({
108 where: {
109 id: projectId,
110 userId: userId,
111 },
112 select: {
113 state: true,
114 draft: true,
115 },
116 });
117 if (r == null) {
118 return null;
119 }
120 let currentState: Graph | null = null;
121 if (state === "deploy") {
122 if (r.state != null) {
gio10ff1342025-07-05 10:22:15 +0000123 currentState = parseGraph(r.state)!.data!;
gio8a5f12f2025-07-05 07:02:31 +0000124 }
125 } else {
126 if (r.draft == null) {
127 if (r.state == null) {
128 currentState = {
129 nodes: [],
130 edges: [],
131 viewport: { x: 0, y: 0, zoom: 1 },
132 };
133 } else {
gio10ff1342025-07-05 10:22:15 +0000134 currentState = parseGraph(r.state)!.data!;
gio8a5f12f2025-07-05 07:02:31 +0000135 }
136 } else {
gio10ff1342025-07-05 10:22:15 +0000137 currentState = parseGraph(r.draft)!.data!;
gio8a5f12f2025-07-05 07:02:31 +0000138 }
139 }
140 return currentState;
141}
142
gio818da4e2025-05-12 14:45:35 +0000143function handleSavedGet(state: "deploy" | "draft"): express.Handler {
144 return async (req, resp) => {
145 try {
gio8a5f12f2025-07-05 07:02:31 +0000146 const projectId = Number(req.params["projectId"]);
147 const graph = await getState(projectId, resp.locals.userId, state);
148 if (graph == null) {
gio818da4e2025-05-12 14:45:35 +0000149 resp.status(404);
150 return;
151 }
gio8a5f12f2025-07-05 07:02:31 +0000152 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
153 const config = generateDodoConfig(projectId.toString(), graph.nodes, env);
giod0026612025-05-08 13:00:36 +0000154 resp.status(200);
155 resp.header("content-type", "application/json");
gio8a5f12f2025-07-05 07:02:31 +0000156 resp.write(
157 JSON.stringify({
158 state: graph,
gioc31bf142025-06-16 07:48:20 +0000159 config,
gio8a5f12f2025-07-05 07:02:31 +0000160 }),
161 );
gio818da4e2025-05-12 14:45:35 +0000162 } catch (e) {
163 console.log(e);
164 resp.status(500);
165 } finally {
166 resp.end();
giod0026612025-05-08 13:00:36 +0000167 }
gio818da4e2025-05-12 14:45:35 +0000168 };
169}
giod0026612025-05-08 13:00:36 +0000170
gioa71316d2025-05-24 09:41:36 +0400171const handleProjectDelete: express.Handler = async (req, resp) => {
giod0026612025-05-08 13:00:36 +0000172 try {
173 const projectId = Number(req.params["projectId"]);
174 const p = await db.project.findUnique({
175 where: {
176 id: projectId,
gio09fcab52025-05-12 14:05:07 +0000177 userId: resp.locals.userId,
giod0026612025-05-08 13:00:36 +0000178 },
179 select: {
180 instanceId: true,
gioa71316d2025-05-24 09:41:36 +0400181 githubToken: true,
182 deployKeyPublic: true,
183 state: true,
184 draft: true,
giod0026612025-05-08 13:00:36 +0000185 },
186 });
187 if (p === null) {
188 resp.status(404);
189 return;
190 }
gioa71316d2025-05-24 09:41:36 +0400191 if (p.githubToken && p.deployKeyPublic) {
gio56e9f472025-07-07 03:33:38 +0000192 const allRepos = [...new Set([...extractGithubRepos(p.state), ...extractGithubRepos(p.draft)])];
gioa71316d2025-05-24 09:41:36 +0400193 if (allRepos.length > 0) {
194 const diff: RepoDiff = { toDelete: allRepos, toAdd: [] };
195 const github = new GithubClient(p.githubToken);
196 await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR);
197 console.log(
198 `Attempted to remove deploy keys for project ${projectId} from associated GitHub repositories.`,
199 );
200 }
giod0026612025-05-08 13:00:36 +0000201 }
gioa71316d2025-05-24 09:41:36 +0400202 if (p.instanceId !== null) {
203 if (!(await appManager.removeInstance(p.instanceId))) {
204 resp.status(500);
205 resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" }));
206 return;
207 }
208 }
209 await db.project.delete({
210 where: {
211 id: projectId,
212 },
213 });
giod0026612025-05-08 13:00:36 +0000214 resp.status(200);
215 } catch (e) {
216 console.log(e);
217 resp.status(500);
218 } finally {
219 resp.end();
220 }
221};
222
gioa71316d2025-05-24 09:41:36 +0400223function extractGithubRepos(serializedState: string | null | undefined): string[] {
gio3ed59592025-05-14 16:51:09 +0000224 if (!serializedState) {
225 return [];
226 }
227 try {
giobd37a2b2025-05-15 04:28:42 +0000228 const stateObj = JSON.parse(serializedState);
gio3ed59592025-05-14 16:51:09 +0000229 const githubNodes = stateObj.nodes.filter(
230 // eslint-disable-next-line @typescript-eslint/no-explicit-any
231 (n: any) => n.type === "github" && n.data?.repository?.id,
232 );
233 // eslint-disable-next-line @typescript-eslint/no-explicit-any
234 return githubNodes.map((n: any) => n.data.repository.sshURL);
235 } catch (error) {
236 console.error("Failed to parse state or extract GitHub repos:", error);
237 return [];
238 }
239}
240
241type RepoDiff = {
242 toAdd?: string[];
243 toDelete?: string[];
244};
245
246function calculateRepoDiff(oldRepos: string[], newRepos: string[]): RepoDiff {
247 const toAdd = newRepos.filter((repo) => !oldRepos.includes(repo));
248 const toDelete = oldRepos.filter((repo) => !newRepos.includes(repo));
249 return { toAdd, toDelete };
250}
251
gio76d8ae62025-05-19 15:21:54 +0000252async function manageGithubRepos(
253 github: GithubClient,
254 diff: RepoDiff,
255 deployKey: string,
256 publicAddr?: string,
257): Promise<void> {
gio3ed59592025-05-14 16:51:09 +0000258 for (const repoUrl of diff.toDelete ?? []) {
259 try {
260 await github.removeDeployKey(repoUrl, deployKey);
261 console.log(`Removed deploy key from repository ${repoUrl}`);
gio76d8ae62025-05-19 15:21:54 +0000262 if (publicAddr) {
263 const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`;
264 await github.removePushWebhook(repoUrl, webhookCallbackUrl);
265 console.log(`Removed push webhook from repository ${repoUrl}`);
266 }
gio3ed59592025-05-14 16:51:09 +0000267 } catch (error) {
268 console.error(`Failed to remove deploy key from repository ${repoUrl}:`, error);
269 }
270 }
271 for (const repoUrl of diff.toAdd ?? []) {
272 try {
273 await github.addDeployKey(repoUrl, deployKey);
274 console.log(`Added deploy key to repository ${repoUrl}`);
gio76d8ae62025-05-19 15:21:54 +0000275 if (publicAddr) {
276 const webhookCallbackUrl = `${publicAddr}/api/webhook/github/push`;
277 await github.addPushWebhook(repoUrl, webhookCallbackUrl);
278 console.log(`Added push webhook to repository ${repoUrl}`);
279 }
gio3ed59592025-05-14 16:51:09 +0000280 } catch (error) {
281 console.error(`Failed to add deploy key from repository ${repoUrl}:`, error);
282 }
283 }
284}
285
giod0026612025-05-08 13:00:36 +0000286const handleDeploy: express.Handler = async (req, resp) => {
287 try {
gio56e9f472025-07-07 03:33:38 +0000288 const reqParsed = GraphConfigOrDraft.safeParse(req.body);
289 if (!reqParsed.success) {
290 resp.status(400);
291 resp.write(JSON.stringify({ error: "Invalid request body", issues: reqParsed.error.format() }));
292 return;
293 }
giod0026612025-05-08 13:00:36 +0000294 const projectId = Number(req.params["projectId"]);
giod0026612025-05-08 13:00:36 +0000295 const p = await db.project.findUnique({
296 where: {
297 id: projectId,
gioc31bf142025-06-16 07:48:20 +0000298 // userId: resp.locals.userId, TODO(gio): validate
giod0026612025-05-08 13:00:36 +0000299 },
300 select: {
301 instanceId: true,
302 githubToken: true,
303 deployKey: true,
gioa71316d2025-05-24 09:41:36 +0400304 deployKeyPublic: true,
gio3ed59592025-05-14 16:51:09 +0000305 state: true,
gio56e9f472025-07-07 03:33:38 +0000306 draft: true,
gio69148322025-06-19 23:16:12 +0400307 geminiApiKey: true,
gio69ff7592025-07-03 06:27:21 +0000308 anthropicApiKey: true,
giod0026612025-05-08 13:00:36 +0000309 },
310 });
311 if (p === null) {
312 resp.status(404);
313 return;
314 }
gio56e9f472025-07-07 03:33:38 +0000315 let graph: Graph | null = null;
316 let config: Config | null = null;
317 if (reqParsed.data.type === "config") {
318 const parsed = ConfigSchema.safeParse(reqParsed.data.config);
319 if (parsed.success) {
320 config = parsed.data;
321 } else {
322 resp.status(400);
323 resp.write(JSON.stringify({ error: "Invalid configuration", issues: parsed.error.format() }));
324 return;
325 }
326 let oldGraph: Graph | undefined = undefined;
327 if (p.state != null) {
328 oldGraph = parseGraph(p.state)!.data;
329 } else if (p.draft != null) {
330 oldGraph = parseGraph(p.draft)!.data;
331 }
332 let repos: GithubRepository[] = [];
333 if (p.githubToken) {
334 const github = new GithubClient(p.githubToken);
335 repos = await github.getRepositories();
336 }
337 graph = configToGraph(config, getNetworks(resp.locals.username), repos, oldGraph);
338 } else if (reqParsed.data.type === "graph") {
339 graph = reqParsed.data.graph;
340 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
341 config = generateDodoConfig(projectId.toString(), graph?.nodes || [], env);
342 } else if (reqParsed.data.type === "draft") {
343 if (p.draft == null) {
344 resp.status(400);
345 resp.write(JSON.stringify({ error: "Invalid request body" }));
346 return;
347 }
348 graph = parseGraph(p.draft)!.data!;
349 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
350 config = generateDodoConfig(projectId.toString(), graph?.nodes || [], env);
351 }
352 if (config == null || graph == null) {
353 resp.status(500);
354 resp.write(JSON.stringify({ error: "Failed to generate configuration" }));
gioc31bf142025-06-16 07:48:20 +0000355 return;
356 }
giod0026612025-05-08 13:00:36 +0000357 await db.project.update({
358 where: {
359 id: projectId,
360 },
361 data: {
gio56e9f472025-07-07 03:33:38 +0000362 draft: JSON.stringify(graph),
giod0026612025-05-08 13:00:36 +0000363 },
364 });
gioa71316d2025-05-24 09:41:36 +0400365 let deployKey: string | null = p.deployKey;
366 let deployKeyPublic: string | null = p.deployKeyPublic;
367 if (deployKeyPublic == null) {
368 [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name);
369 await db.project.update({
370 where: { id: projectId },
371 data: { deployKeyPublic, deployKey },
372 });
373 }
gio3ed59592025-05-14 16:51:09 +0000374 let diff: RepoDiff | null = null;
gioc31bf142025-06-16 07:48:20 +0000375 const cfg: ConfigWithInput = {
gio56e9f472025-07-07 03:33:38 +0000376 ...config,
gioc31bf142025-06-16 07:48:20 +0000377 input: {
378 appId: projectId.toString(),
379 managerAddr: env.INTERNAL_API_ADDR!,
380 key: {
381 public: deployKeyPublic!,
382 private: deployKey!,
383 },
gio69148322025-06-19 23:16:12 +0400384 geminiApiKey: p.geminiApiKey ?? undefined,
gio69ff7592025-07-03 06:27:21 +0000385 anthropicApiKey: p.anthropicApiKey ?? undefined,
gioc31bf142025-06-16 07:48:20 +0000386 },
gioa71316d2025-05-24 09:41:36 +0400387 };
gio3ed59592025-05-14 16:51:09 +0000388 try {
gioe085d5b2025-07-08 07:51:36 +0000389 let deployResponse: DeployResponse | null = null;
gio3ed59592025-05-14 16:51:09 +0000390 if (p.instanceId == null) {
gioe085d5b2025-07-08 07:51:36 +0000391 deployResponse = await appManager.deploy(cfg);
gio56e9f472025-07-07 03:33:38 +0000392 diff = { toAdd: extractGithubRepos(JSON.stringify(graph)) };
gio3ed59592025-05-14 16:51:09 +0000393 } else {
gioe085d5b2025-07-08 07:51:36 +0000394 deployResponse = await appManager.update(p.instanceId, cfg);
gio56e9f472025-07-07 03:33:38 +0000395 diff = calculateRepoDiff(extractGithubRepos(p.state), extractGithubRepos(JSON.stringify(graph)));
giod0026612025-05-08 13:00:36 +0000396 }
gioe085d5b2025-07-08 07:51:36 +0000397 if (deployResponse == null) {
398 resp.status(500);
399 resp.write(JSON.stringify({ error: "Failed to deploy" }));
400 return;
401 }
402 await db.project.update({
403 where: {
404 id: projectId,
405 },
406 data: {
407 state: JSON.stringify(graph),
408 draft: null,
409 instanceId: deployResponse.id,
410 access: JSON.stringify(deployResponse.access),
411 envVars: JSON.stringify(deployResponse.envVars),
412 },
413 });
gio3ed59592025-05-14 16:51:09 +0000414 if (diff && p.githubToken && deployKey) {
415 const github = new GithubClient(p.githubToken);
gioa71316d2025-05-24 09:41:36 +0400416 await manageGithubRepos(github, diff, deployKeyPublic!, env.PUBLIC_ADDR);
giod0026612025-05-08 13:00:36 +0000417 }
gio3ed59592025-05-14 16:51:09 +0000418 resp.status(200);
419 } catch (error) {
420 console.error("Deployment error:", error);
421 resp.status(500);
422 resp.write(JSON.stringify({ error: "Deployment failed" }));
giod0026612025-05-08 13:00:36 +0000423 }
424 } catch (e) {
425 console.log(e);
426 resp.status(500);
427 } finally {
428 resp.end();
429 }
430};
431
gio10ff1342025-07-05 10:22:15 +0000432const handleSave: express.Handler = async (req, resp) => {
gio8a5f12f2025-07-05 07:02:31 +0000433 try {
434 const projectId = Number(req.params["projectId"]);
435 const p = await db.project.findUnique({
436 where: {
437 id: projectId,
gio10ff1342025-07-05 10:22:15 +0000438 userId: resp.locals.userId,
gio8a5f12f2025-07-05 07:02:31 +0000439 },
440 select: {
441 instanceId: true,
442 githubToken: true,
443 deployKey: true,
444 deployKeyPublic: true,
445 state: true,
446 geminiApiKey: true,
447 anthropicApiKey: true,
448 },
449 });
450 if (p === null) {
451 resp.status(404);
452 return;
453 }
gio10ff1342025-07-05 10:22:15 +0000454 const gc = GraphOrConfigSchema.safeParse(req.body);
455 if (!gc.success) {
gio8a5f12f2025-07-05 07:02:31 +0000456 resp.status(400);
gio10ff1342025-07-05 10:22:15 +0000457 resp.write(JSON.stringify({ error: "Invalid configuration", issues: gc.error.format() }));
458 return;
459 }
460 if (gc.data.type === "graph") {
461 await db.project.update({
462 where: { id: projectId },
463 data: { draft: JSON.stringify(gc.data.graph) },
464 });
465 resp.status(200);
gio8a5f12f2025-07-05 07:02:31 +0000466 return;
467 }
468 let repos: GithubRepository[] = [];
469 if (p.githubToken) {
470 const github = new GithubClient(p.githubToken);
471 repos = await github.getRepositories();
472 }
473 const state = JSON.stringify(
474 configToGraph(
gio10ff1342025-07-05 10:22:15 +0000475 gc.data.config,
gio8a5f12f2025-07-05 07:02:31 +0000476 getNetworks(resp.locals.username),
477 repos,
gio10ff1342025-07-05 10:22:15 +0000478 p.state ? parseGraph(p.state)!.data! : undefined,
gio8a5f12f2025-07-05 07:02:31 +0000479 ),
480 );
481 await db.project.update({
482 where: { id: projectId },
483 data: { draft: state },
484 });
485 resp.status(200);
486 } catch (e) {
487 console.log(e);
488 resp.status(500);
489 } finally {
490 resp.end();
491 }
492};
493
giod0026612025-05-08 13:00:36 +0000494const handleStatus: express.Handler = async (req, resp) => {
495 try {
496 const projectId = Number(req.params["projectId"]);
497 const p = await db.project.findUnique({
498 where: {
499 id: projectId,
gio09fcab52025-05-12 14:05:07 +0000500 userId: resp.locals.userId,
giod0026612025-05-08 13:00:36 +0000501 },
502 select: {
503 instanceId: true,
504 },
505 });
giod0026612025-05-08 13:00:36 +0000506 if (p === null) {
507 resp.status(404);
508 return;
509 }
510 if (p.instanceId == null) {
511 resp.status(404);
512 return;
513 }
gio3ed59592025-05-14 16:51:09 +0000514 try {
515 const status = await appManager.getStatus(p.instanceId);
516 resp.status(200);
517 resp.write(JSON.stringify(status));
518 } catch (error) {
519 console.error("Error getting status:", error);
520 resp.status(500);
giod0026612025-05-08 13:00:36 +0000521 }
522 } catch (e) {
523 console.log(e);
524 resp.status(500);
525 } finally {
526 resp.end();
527 }
528};
529
gioc31bf142025-06-16 07:48:20 +0000530const handleConfigGet: express.Handler = async (req, resp) => {
531 try {
532 const projectId = Number(req.params["projectId"]);
533 const project = await db.project.findUnique({
534 where: {
535 id: projectId,
536 },
537 select: {
538 state: true,
539 },
540 });
541
542 if (!project || !project.state) {
543 resp.status(404).send({ error: "No deployed configuration found." });
544 return;
545 }
546
gio10ff1342025-07-05 10:22:15 +0000547 const state = parseGraph(project.state)!.data!;
gioc31bf142025-06-16 07:48:20 +0000548 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
549 const config = generateDodoConfig(projectId.toString(), state.nodes, env);
550
551 if (!config) {
552 resp.status(500).send({ error: "Failed to generate configuration." });
553 return;
554 }
555 resp.status(200).json(config);
556 } catch (e) {
557 console.log(e);
558 resp.status(500).send({ error: "Internal server error" });
559 } finally {
560 console.log("config get done");
561 resp.end();
562 }
563};
564
giobd37a2b2025-05-15 04:28:42 +0000565const handleRemoveDeployment: express.Handler = async (req, resp) => {
566 try {
567 const projectId = Number(req.params["projectId"]);
568 const p = await db.project.findUnique({
569 where: {
570 id: projectId,
571 userId: resp.locals.userId,
572 },
573 select: {
574 instanceId: true,
575 githubToken: true,
gioa71316d2025-05-24 09:41:36 +0400576 deployKeyPublic: true,
giobd37a2b2025-05-15 04:28:42 +0000577 state: true,
578 draft: true,
579 },
580 });
581 if (p === null) {
582 resp.status(404);
583 resp.write(JSON.stringify({ error: "Project not found" }));
584 return;
585 }
586 if (p.instanceId == null) {
587 resp.status(400);
588 resp.write(JSON.stringify({ error: "Project not deployed" }));
589 return;
590 }
591 const removed = await appManager.removeInstance(p.instanceId);
592 if (!removed) {
593 resp.status(500);
594 resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" }));
595 return;
596 }
gioa71316d2025-05-24 09:41:36 +0400597 if (p.githubToken && p.deployKeyPublic && p.state) {
giobd37a2b2025-05-15 04:28:42 +0000598 try {
599 const github = new GithubClient(p.githubToken);
600 const repos = extractGithubRepos(p.state);
601 const diff = { toDelete: repos, toAdd: [] };
gioa71316d2025-05-24 09:41:36 +0400602 await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR);
giobd37a2b2025-05-15 04:28:42 +0000603 } catch (error) {
604 console.error("Error removing GitHub deploy keys:", error);
605 }
606 }
607 await db.project.update({
608 where: {
609 id: projectId,
610 },
611 data: {
612 instanceId: null,
gioa71316d2025-05-24 09:41:36 +0400613 deployKeyPublic: null,
giob77cb932025-05-19 09:37:14 +0000614 access: null,
giobd37a2b2025-05-15 04:28:42 +0000615 state: null,
616 draft: p.draft ?? p.state,
617 },
618 });
619 resp.status(200);
620 resp.write(JSON.stringify({ success: true }));
621 } catch (e) {
622 console.error("Error removing deployment:", e);
623 resp.status(500);
624 resp.write(JSON.stringify({ error: "Internal server error" }));
625 } finally {
626 resp.end();
627 }
628};
629
giod0026612025-05-08 13:00:36 +0000630const handleGithubRepos: express.Handler = async (req, resp) => {
631 try {
632 const projectId = Number(req.params["projectId"]);
633 const project = await db.project.findUnique({
gio09fcab52025-05-12 14:05:07 +0000634 where: {
635 id: projectId,
636 userId: resp.locals.userId,
637 },
638 select: {
639 githubToken: true,
640 },
giod0026612025-05-08 13:00:36 +0000641 });
giod0026612025-05-08 13:00:36 +0000642 if (!project?.githubToken) {
643 resp.status(400);
644 resp.write(JSON.stringify({ error: "GitHub token not configured" }));
645 return;
646 }
giod0026612025-05-08 13:00:36 +0000647 const github = new GithubClient(project.githubToken);
648 const repositories = await github.getRepositories();
giod0026612025-05-08 13:00:36 +0000649 resp.status(200);
650 resp.header("Content-Type", "application/json");
651 resp.write(JSON.stringify(repositories));
652 } catch (e) {
653 console.log(e);
654 resp.status(500);
655 resp.write(JSON.stringify({ error: "Failed to fetch repositories" }));
656 } finally {
657 resp.end();
658 }
659};
660
661const handleUpdateGithubToken: express.Handler = async (req, resp) => {
662 try {
giod0026612025-05-08 13:00:36 +0000663 await db.project.update({
gio09fcab52025-05-12 14:05:07 +0000664 where: {
gio69148322025-06-19 23:16:12 +0400665 id: Number(req.params["projectId"]),
gio09fcab52025-05-12 14:05:07 +0000666 userId: resp.locals.userId,
667 },
gio69148322025-06-19 23:16:12 +0400668 data: {
669 githubToken: req.body.githubToken,
670 },
671 });
672 resp.status(200);
673 } catch (e) {
674 console.log(e);
675 resp.status(500);
676 } finally {
677 resp.end();
678 }
679};
680
681const handleUpdateGeminiToken: express.Handler = async (req, resp) => {
682 try {
683 await db.project.update({
684 where: {
685 id: Number(req.params["projectId"]),
686 userId: resp.locals.userId,
687 },
688 data: {
689 geminiApiKey: req.body.geminiApiKey,
690 },
giod0026612025-05-08 13:00:36 +0000691 });
giod0026612025-05-08 13:00:36 +0000692 resp.status(200);
693 } catch (e) {
694 console.log(e);
695 resp.status(500);
696 } finally {
697 resp.end();
698 }
699};
700
gio69ff7592025-07-03 06:27:21 +0000701const handleUpdateAnthropicToken: express.Handler = async (req, resp) => {
702 try {
703 await db.project.update({
704 where: {
705 id: Number(req.params["projectId"]),
706 userId: resp.locals.userId,
707 },
708 data: {
709 anthropicApiKey: req.body.anthropicApiKey,
710 },
711 });
712 resp.status(200);
713 } catch (e) {
714 console.log(e);
715 resp.status(500);
716 } finally {
717 resp.end();
718 }
719};
720
gioc31bf142025-06-16 07:48:20 +0000721const getNetworks = (username?: string | undefined): Network[] => {
722 return [
723 {
724 name: "Trial",
725 domain: "trial.dodoapp.xyz",
726 hasAuth: false,
727 },
728 // TODO(gio): Remove
729 ].concat(
730 username === "gio" || 1 == 1
731 ? [
732 {
733 name: "Public",
734 domain: "v1.dodo.cloud",
735 hasAuth: true,
736 },
737 {
738 name: "Private",
739 domain: "p.v1.dodo.cloud",
740 hasAuth: true,
741 },
742 ]
743 : [],
744 );
745};
746
747const getEnv = async (projectId: number, userId: string, username: string): Promise<Env> => {
748 const project = await db.project.findUnique({
749 where: {
750 id: projectId,
751 userId,
752 },
753 select: {
754 deployKeyPublic: true,
755 githubToken: true,
gio69148322025-06-19 23:16:12 +0400756 geminiApiKey: true,
gio69ff7592025-07-03 06:27:21 +0000757 anthropicApiKey: true,
gioc31bf142025-06-16 07:48:20 +0000758 access: true,
759 instanceId: true,
760 },
761 });
762 if (!project) {
763 throw new Error("Project not found");
764 }
765 const monitor = projectMonitors.get(projectId);
766 const serviceNames = monitor ? monitor.getAllServiceNames() : [];
767 const services = serviceNames.map((name: string) => ({
768 name,
769 workers: [...(monitor ? monitor.getWorkerStatusesForService(name) : new Map()).entries()].map(
770 ([id, status]) => ({
771 ...status,
772 id,
773 }),
774 ),
775 }));
776 return {
gioc31bf142025-06-16 07:48:20 +0000777 deployKeyPublic: project.deployKeyPublic == null ? undefined : project.deployKeyPublic,
778 instanceId: project.instanceId == null ? undefined : project.instanceId,
779 access: JSON.parse(project.access ?? "[]"),
780 integrations: {
781 github: !!project.githubToken,
gio69148322025-06-19 23:16:12 +0400782 gemini: !!project.geminiApiKey,
gio69ff7592025-07-03 06:27:21 +0000783 anthropic: !!project.anthropicApiKey,
gioc31bf142025-06-16 07:48:20 +0000784 },
785 networks: getNetworks(username),
786 services,
787 user: {
788 id: userId,
789 username: username,
790 },
791 };
792};
793
giod0026612025-05-08 13:00:36 +0000794const handleEnv: express.Handler = async (req, resp) => {
795 const projectId = Number(req.params["projectId"]);
796 try {
gioc31bf142025-06-16 07:48:20 +0000797 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
giod0026612025-05-08 13:00:36 +0000798 resp.status(200);
gioc31bf142025-06-16 07:48:20 +0000799 resp.write(JSON.stringify(env));
giod0026612025-05-08 13:00:36 +0000800 } catch (error) {
gioc31bf142025-06-16 07:48:20 +0000801 console.error("Error getting env:", error);
giod0026612025-05-08 13:00:36 +0000802 resp.status(500);
803 resp.write(JSON.stringify({ error: "Internal server error" }));
804 } finally {
805 resp.end();
806 }
807};
808
gio007c8572025-07-08 04:27:35 +0000809// eslint-disable-next-line @typescript-eslint/no-unused-vars
810const internalEnvSchema = z.object({
811 githubToken: z.string().optional(),
812 networks: z.array(
813 z.object({
814 name: z.string(),
815 domain: z.string(),
816 hasAuth: z.boolean(),
817 }),
818 ),
gioe085d5b2025-07-08 07:51:36 +0000819 envVars: z.array(z.object({ name: z.string(), value: z.string() })),
gio007c8572025-07-08 04:27:35 +0000820});
821
822type InternalEnv = z.infer<typeof internalEnvSchema>;
823
824const handleInternalEnv: express.Handler = async (req, resp) => {
825 try {
826 console.log("getting internal env");
827 const project = await db.project.findUnique({
828 where: {
829 id: Number(req.params["projectId"]),
830 userId: resp.locals.userId,
831 },
832 select: {
833 githubToken: true,
gioe085d5b2025-07-08 07:51:36 +0000834 envVars: true,
gio007c8572025-07-08 04:27:35 +0000835 },
836 });
837 const networks = getNetworks(resp.locals.username);
838 const env: InternalEnv = {
839 networks,
840 githubToken: project?.githubToken ?? undefined,
gioe085d5b2025-07-08 07:51:36 +0000841 envVars: JSON.parse(project?.envVars ?? "[]"),
gio007c8572025-07-08 04:27:35 +0000842 };
843 resp.status(200);
844 resp.write(JSON.stringify(env));
845 } catch (error) {
846 console.error("Error getting env:", error);
847 resp.status(500);
848 resp.write(JSON.stringify({ error: "Internal server error" }));
849 } finally {
850 resp.end();
851 }
852};
853
gio3a921b82025-05-10 07:36:09 +0000854const handleServiceLogs: express.Handler = async (req, resp) => {
gio78a22882025-07-01 18:56:01 +0000855 const projectId = Number(req.params["projectId"]);
856 const service = req.params["service"];
857 const workerId = req.params["workerId"];
858
859 resp.setHeader("Content-Type", "text/event-stream");
860 resp.setHeader("Cache-Control", "no-cache");
861 resp.setHeader("Connection", "keep-alive");
862 resp.flushHeaders();
863
864 const timestampFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
865 const sendLogs = (logs: LogItem[]) => {
866 if (logs.length == 0) {
867 return;
868 }
869 const logString = logs
870 .map((l) => {
871 const t = Instant.ofEpochMilli(l.timestampMilli);
872 const formattedTimestamp = t.atZone(ZoneId.UTC).format(timestampFormat);
873 return `\x1b[38;5;240m${formattedTimestamp}\x1b[0m ${l.contents}`;
874 })
875 .join("\n");
876 resp.write("event: message\n");
877 resp.write(`data: ${JSON.stringify({ logs: logString })}\n\n`);
878 };
879
gio3a921b82025-05-10 07:36:09 +0000880 try {
gio09fcab52025-05-12 14:05:07 +0000881 const project = await db.project.findUnique({
gio78a22882025-07-01 18:56:01 +0000882 where: { id: projectId, userId: resp.locals.userId },
gio09fcab52025-05-12 14:05:07 +0000883 });
gio78a22882025-07-01 18:56:01 +0000884
885 if (!project) {
886 resp.status(404).end();
gio09fcab52025-05-12 14:05:07 +0000887 return;
888 }
gio78a22882025-07-01 18:56:01 +0000889
gioa1efbad2025-05-21 07:16:45 +0000890 const monitor = projectMonitors.get(projectId);
gio78a22882025-07-01 18:56:01 +0000891 if (!monitor) {
892 resp.status(404).end();
gio3a921b82025-05-10 07:36:09 +0000893 return;
894 }
gio78a22882025-07-01 18:56:01 +0000895
gio40c0c992025-07-02 13:18:05 +0000896 let lastLogId: number | undefined = undefined;
897 const initialLogs = (await logStore.get(projectId, service, workerId)) || [];
gio8a5f12f2025-07-05 07:02:31 +0000898 await sendLogs(initialLogs);
gio40c0c992025-07-02 13:18:05 +0000899 if (initialLogs.length > 0) {
900 lastLogId = initialLogs[initialLogs.length - 1].id;
901 }
gio78a22882025-07-01 18:56:01 +0000902 resp.flushHeaders();
903
gio40c0c992025-07-02 13:18:05 +0000904 const intervalId = setInterval(async () => {
905 const currentLogs = (await logStore.get(projectId, service, workerId, lastLogId)) || [];
906 if (currentLogs.length > 0) {
gio8a5f12f2025-07-05 07:02:31 +0000907 await sendLogs(currentLogs);
gio40c0c992025-07-02 13:18:05 +0000908 lastLogId = currentLogs[currentLogs.length - 1].id;
gio78a22882025-07-01 18:56:01 +0000909 }
910 }, 500);
911
912 req.on("close", () => {
913 clearInterval(intervalId);
914 resp.end();
915 });
gio3a921b82025-05-10 07:36:09 +0000916 } catch (e) {
917 console.log(e);
gio78a22882025-07-01 18:56:01 +0000918 resp.status(500).end();
gio3a921b82025-05-10 07:36:09 +0000919 }
920};
921
gio7d813702025-05-08 18:29:52 +0000922const handleRegisterWorker: express.Handler = async (req, resp) => {
923 try {
924 const projectId = Number(req.params["projectId"]);
gio7d813702025-05-08 18:29:52 +0000925 const result = WorkerSchema.safeParse(req.body);
gio7d813702025-05-08 18:29:52 +0000926 if (!result.success) {
gioa70535a2025-07-02 15:50:25 +0000927 console.log(JSON.stringify(result.error));
gio7d813702025-05-08 18:29:52 +0000928 resp.status(400);
929 resp.write(
930 JSON.stringify({
931 error: "Invalid request data",
932 details: result.error.format(),
933 }),
934 );
935 return;
936 }
gioa1efbad2025-05-21 07:16:45 +0000937 let monitor = projectMonitors.get(projectId);
938 if (!monitor) {
939 monitor = new ProjectMonitor();
940 projectMonitors.set(projectId, monitor);
gio7d813702025-05-08 18:29:52 +0000941 }
gioa1efbad2025-05-21 07:16:45 +0000942 monitor.registerWorker(result.data);
gio40c0c992025-07-02 13:18:05 +0000943 if (result.data.logs) {
944 await logStore.store(projectId, result.data.service, result.data.id, result.data.logs);
945 }
gio7d813702025-05-08 18:29:52 +0000946 resp.status(200);
947 resp.write(
948 JSON.stringify({
949 success: true,
gio78a22882025-07-01 18:56:01 +0000950 logItemsConsumed: result.data.logs?.length ?? 0,
gio7d813702025-05-08 18:29:52 +0000951 }),
952 );
953 } catch (e) {
954 console.log(e);
955 resp.status(500);
956 resp.write(JSON.stringify({ error: "Failed to register worker" }));
957 } finally {
958 resp.end();
959 }
960};
961
gio76d8ae62025-05-19 15:21:54 +0000962async function reloadProject(projectId: number): Promise<boolean> {
gioa1efbad2025-05-21 07:16:45 +0000963 const monitor = projectMonitors.get(projectId);
964 const projectWorkers = monitor ? monitor.getWorkerAddresses() : [];
gio76d8ae62025-05-19 15:21:54 +0000965 const workerCount = projectWorkers.length;
966 if (workerCount === 0) {
967 return true;
968 }
969 const results = await Promise.all(
gioc31bf142025-06-16 07:48:20 +0000970 projectWorkers.map(async (workerAddress: string) => {
971 try {
972 const { data } = await axios.get(`http://${workerAddress}/reload`);
973 return data.every((s: { status: string }) => s.status === "ok");
974 } catch (error) {
975 console.error(`Failed to reload worker ${workerAddress}:`, error);
976 return false;
977 }
gio76d8ae62025-05-19 15:21:54 +0000978 }),
979 );
gioc31bf142025-06-16 07:48:20 +0000980 return results.reduce((acc: boolean, curr: boolean) => acc && curr, true);
gio76d8ae62025-05-19 15:21:54 +0000981}
982
gio7d813702025-05-08 18:29:52 +0000983const handleReload: express.Handler = async (req, resp) => {
984 try {
985 const projectId = Number(req.params["projectId"]);
gio76d8ae62025-05-19 15:21:54 +0000986 const projectAuth = await db.project.findFirst({
gio09fcab52025-05-12 14:05:07 +0000987 where: {
988 id: projectId,
989 userId: resp.locals.userId,
990 },
gio76d8ae62025-05-19 15:21:54 +0000991 select: { id: true },
gio09fcab52025-05-12 14:05:07 +0000992 });
gio76d8ae62025-05-19 15:21:54 +0000993 if (!projectAuth) {
gio09fcab52025-05-12 14:05:07 +0000994 resp.status(404);
gio09fcab52025-05-12 14:05:07 +0000995 return;
996 }
gio76d8ae62025-05-19 15:21:54 +0000997 const success = await reloadProject(projectId);
998 if (success) {
999 resp.status(200);
1000 } else {
1001 resp.status(500);
gio7d813702025-05-08 18:29:52 +00001002 }
gio7d813702025-05-08 18:29:52 +00001003 } catch (e) {
gio76d8ae62025-05-19 15:21:54 +00001004 console.error(e);
gio7d813702025-05-08 18:29:52 +00001005 resp.status(500);
gio7d813702025-05-08 18:29:52 +00001006 }
1007};
1008
gio577d2342025-07-03 12:50:18 +00001009const handleQuitWorker: express.Handler = async (req, resp) => {
1010 const projectId = Number(req.params["projectId"]);
1011 const serviceName = req.params["serviceName"];
1012 const workerId = req.params["workerId"];
1013
1014 const projectMonitor = projectMonitors.get(projectId);
1015 if (!projectMonitor) {
1016 resp.status(404).send({ error: "Project monitor not found" });
1017 return;
1018 }
1019
1020 try {
1021 await projectMonitor.terminateWorker(serviceName, workerId);
1022 resp.status(200).send({ message: "Worker termination initiated" });
1023 } catch (error) {
1024 console.error(
1025 `Failed to terminate worker ${workerId} in service ${serviceName} for project ${projectId}:`,
1026 error,
1027 );
1028 const errorMessage = error instanceof Error ? error.message : "Unknown error";
1029 resp.status(500).send({ error: `Failed to terminate worker: ${errorMessage}` });
1030 }
1031};
1032
gio918780d2025-05-22 08:24:41 +00001033const handleReloadWorker: express.Handler = async (req, resp) => {
1034 const projectId = Number(req.params["projectId"]);
1035 const serviceName = req.params["serviceName"];
1036 const workerId = req.params["workerId"];
1037
1038 const projectMonitor = projectMonitors.get(projectId);
1039 if (!projectMonitor) {
1040 resp.status(404).send({ error: "Project monitor not found" });
1041 return;
1042 }
1043
1044 try {
1045 await projectMonitor.reloadWorker(serviceName, workerId);
1046 resp.status(200).send({ message: "Worker reload initiated" });
1047 } catch (error) {
1048 console.error(`Failed to reload worker ${workerId} in service ${serviceName} for project ${projectId}:`, error);
1049 const errorMessage = error instanceof Error ? error.message : "Unknown error";
1050 resp.status(500).send({ error: `Failed to reload worker: ${errorMessage}` });
1051 }
1052};
1053
gioa71316d2025-05-24 09:41:36 +04001054const analyzeRepoReqSchema = z.object({
1055 address: z.string(),
1056});
1057
1058const handleAnalyzeRepo: express.Handler = async (req, resp) => {
1059 const projectId = Number(req.params["projectId"]);
1060 const project = await db.project.findUnique({
1061 where: {
1062 id: projectId,
1063 userId: resp.locals.userId,
1064 },
1065 select: {
1066 githubToken: true,
1067 deployKey: true,
1068 deployKeyPublic: true,
1069 },
1070 });
1071 if (!project) {
1072 resp.status(404).send({ error: "Project not found" });
1073 return;
1074 }
1075 if (!project.githubToken) {
1076 resp.status(400).send({ error: "GitHub token not configured" });
1077 return;
1078 }
gio8e74dc02025-06-13 10:19:26 +00001079 let tmpDir: tmp.DirResult | null = null;
1080 try {
1081 let deployKey: string | null = project.deployKey;
1082 let deployKeyPublic: string | null = project.deployKeyPublic;
1083 if (!deployKeyPublic) {
1084 [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name);
1085 await db.project.update({
1086 where: { id: projectId },
1087 data: {
1088 deployKeyPublic: deployKeyPublic,
1089 deployKey: deployKey,
1090 },
1091 });
1092 }
1093 const github = new GithubClient(project.githubToken);
1094 const result = analyzeRepoReqSchema.safeParse(req.body);
1095 if (!result.success) {
1096 resp.status(400).send({ error: "Invalid request data" });
1097 return;
1098 }
1099 const { address } = result.data;
1100 tmpDir = tmp.dirSync({
1101 unsafeCleanup: true,
gioa71316d2025-05-24 09:41:36 +04001102 });
gio8e74dc02025-06-13 10:19:26 +00001103 await github.addDeployKey(address, deployKeyPublic);
1104 await fs.promises.writeFile(path.join(tmpDir.name, "key"), deployKey!, {
1105 mode: 0o600,
1106 });
1107 shell.exec(
1108 `GIT_SSH_COMMAND='ssh -i ${tmpDir.name}/key -o IdentitiesOnly=yes' git clone ${address} ${tmpDir.name}/code`,
1109 );
1110 const fsc = new RealFileSystem(`${tmpDir.name}/code`);
1111 const analyzer = new NodeJSAnalyzer();
1112 const info = await analyzer.analyze(fsc, "/");
1113 resp.status(200).send([info]);
1114 } catch (e) {
1115 console.error(e);
1116 resp.status(500).send({ error: "Failed to analyze repository" });
1117 } finally {
1118 if (tmpDir) {
1119 tmpDir.removeCallback();
1120 }
1121 resp.end();
gioa71316d2025-05-24 09:41:36 +04001122 }
gioa71316d2025-05-24 09:41:36 +04001123};
1124
gio09fcab52025-05-12 14:05:07 +00001125const auth = (req: express.Request, resp: express.Response, next: express.NextFunction) => {
gio69148322025-06-19 23:16:12 +04001126 // Hardcoded user for development
1127 resp.locals.userId = "1";
1128 resp.locals.username = "gio";
gio09fcab52025-05-12 14:05:07 +00001129 next();
1130};
1131
gio76d8ae62025-05-19 15:21:54 +00001132const handleGithubPushWebhook: express.Handler = async (req, resp) => {
1133 try {
1134 // TODO(gio): Implement GitHub signature verification for security
1135 const webhookSchema = z.object({
1136 repository: z.object({
1137 ssh_url: z.string(),
1138 }),
1139 });
1140
1141 const result = webhookSchema.safeParse(req.body);
1142 if (!result.success) {
1143 console.warn("GitHub webhook: Invalid payload:", result.error.issues);
1144 resp.status(400).json({ error: "Invalid webhook payload" });
1145 return;
1146 }
1147 const { ssh_url: addr } = result.data.repository;
1148 const allProjects = await db.project.findMany({
1149 select: {
1150 id: true,
1151 state: true,
1152 },
1153 where: {
1154 instanceId: {
1155 not: null,
1156 },
1157 },
1158 });
1159 // TODO(gio): This should run in background
1160 new Promise<boolean>((resolve, reject) => {
1161 setTimeout(() => {
1162 const projectsToReloadIds: number[] = [];
1163 for (const project of allProjects) {
1164 if (project.state && project.state.length > 0) {
1165 const projectRepos = extractGithubRepos(project.state);
1166 if (projectRepos.includes(addr)) {
1167 projectsToReloadIds.push(project.id);
1168 }
1169 }
1170 }
1171 Promise.all(projectsToReloadIds.map((id) => reloadProject(id)))
1172 .then((results) => {
1173 resolve(results.reduce((acc, curr) => acc && curr, true));
1174 })
1175 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1176 .catch((reason: any) => reject(reason));
1177 }, 10);
1178 });
1179 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1180 } catch (error: any) {
1181 console.error(error);
1182 resp.status(500);
1183 }
1184};
1185
gioc31bf142025-06-16 07:48:20 +00001186const handleValidateConfig: express.Handler = async (req, resp) => {
1187 try {
1188 const validationResult = ConfigSchema.safeParse(req.body);
1189 if (!validationResult.success) {
1190 resp.status(400);
1191 resp.header("Content-Type", "application/json");
1192 resp.write(JSON.stringify({ success: false, errors: validationResult.error.flatten() }));
1193 } else {
1194 resp.status(200);
1195 resp.header("Content-Type", "application/json");
1196 resp.write(JSON.stringify({ success: true }));
1197 }
1198 } catch (e) {
1199 console.log(e);
1200 resp.status(500);
1201 } finally {
1202 resp.end();
1203 }
1204};
1205
gio8a5f12f2025-07-05 07:02:31 +00001206function handleStateGetStream(state: "deploy" | "draft"): express.Handler {
1207 return async (req, resp) => {
1208 resp.setHeader("Content-Type", "text/event-stream");
1209 resp.setHeader("Cache-Control", "no-cache");
1210 resp.setHeader("Connection", "keep-alive");
1211 resp.flushHeaders();
1212
1213 try {
1214 let intervalId: NodeJS.Timeout | null = null;
1215 let lastState: Graph | null = null;
1216 const sendState = async () => {
1217 const currentState = await getState(Number(req.params["projectId"]), resp.locals.userId, state);
1218 if (currentState == null) {
1219 resp.status(404).end();
1220 return;
1221 }
1222 if (JSON.stringify(currentState) !== JSON.stringify(lastState)) {
1223 lastState = currentState;
1224 resp.write("event: message\n");
1225 resp.write(`data: ${JSON.stringify(currentState)}\n\n`);
1226 }
1227 intervalId = setTimeout(sendState, 500);
1228 };
1229
1230 await sendState();
1231
1232 req.on("close", () => {
1233 if (intervalId) {
1234 clearTimeout(intervalId);
1235 }
1236 resp.end();
1237 });
1238 } catch (e) {
1239 console.log(e);
1240 resp.end();
1241 }
1242 };
1243}
1244
gio785c9882025-07-07 16:40:25 +00001245const handleAgentStatus: express.Handler = async (req, resp) => {
1246 const projectId = Number(req.params["projectId"]);
1247 const agentName = req.params["agentName"];
1248 try {
1249 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
1250 const agent = env.access.find((a): a is AgentAccess => a.type === "https" && a.agentName === agentName);
1251 if (!agent) {
1252 resp.status(404).send({ status: 404 });
1253 return;
1254 }
1255 const agentResp = await axios.get(agent.address);
1256 resp.status(200).send({ status: agentResp.status });
1257 } catch {
1258 resp.status(200).send({ status: 500 });
1259 }
1260};
1261
giod0026612025-05-08 13:00:36 +00001262async function start() {
1263 await db.$connect();
1264 const app = express();
gioc31bf142025-06-16 07:48:20 +00001265 app.set("json spaces", 2);
gio76d8ae62025-05-19 15:21:54 +00001266 app.use(express.json()); // Global JSON parsing
1267
1268 // Public webhook route - no auth needed
1269 app.post("/api/webhook/github/push", handleGithubPushWebhook);
1270
1271 // Authenticated project routes
1272 const projectRouter = express.Router();
gioa71316d2025-05-24 09:41:36 +04001273 projectRouter.use(auth);
1274 projectRouter.post("/:projectId/analyze", handleAnalyzeRepo);
gio76d8ae62025-05-19 15:21:54 +00001275 projectRouter.post("/:projectId/saved", handleSave);
gio8a5f12f2025-07-05 07:02:31 +00001276 projectRouter.get("/:projectId/state/stream/deploy", handleStateGetStream("deploy"));
1277 projectRouter.get("/:projectId/state/stream/draft", handleStateGetStream("draft"));
gio76d8ae62025-05-19 15:21:54 +00001278 projectRouter.get("/:projectId/saved/deploy", handleSavedGet("deploy"));
1279 projectRouter.get("/:projectId/saved/draft", handleSavedGet("draft"));
1280 projectRouter.post("/:projectId/deploy", handleDeploy);
1281 projectRouter.get("/:projectId/status", handleStatus);
gioc31bf142025-06-16 07:48:20 +00001282 projectRouter.get("/:projectId/config", handleConfigGet);
gioa71316d2025-05-24 09:41:36 +04001283 projectRouter.delete("/:projectId", handleProjectDelete);
gio76d8ae62025-05-19 15:21:54 +00001284 projectRouter.get("/:projectId/repos/github", handleGithubRepos);
1285 projectRouter.post("/:projectId/github-token", handleUpdateGithubToken);
gio69148322025-06-19 23:16:12 +04001286 projectRouter.post("/:projectId/gemini-token", handleUpdateGeminiToken);
gio69ff7592025-07-03 06:27:21 +00001287 projectRouter.post("/:projectId/anthropic-token", handleUpdateAnthropicToken);
gio76d8ae62025-05-19 15:21:54 +00001288 projectRouter.get("/:projectId/env", handleEnv);
gio918780d2025-05-22 08:24:41 +00001289 projectRouter.post("/:projectId/reload/:serviceName/:workerId", handleReloadWorker);
gio577d2342025-07-03 12:50:18 +00001290 projectRouter.post("/:projectId/quitquitquit/:serviceName/:workerId", handleQuitWorker);
gio76d8ae62025-05-19 15:21:54 +00001291 projectRouter.post("/:projectId/reload", handleReload);
gioa1efbad2025-05-21 07:16:45 +00001292 projectRouter.get("/:projectId/logs/:service/:workerId", handleServiceLogs);
gio785c9882025-07-07 16:40:25 +00001293 projectRouter.get("/:projectId/agent/:agentName/status", handleAgentStatus);
gio76d8ae62025-05-19 15:21:54 +00001294 projectRouter.post("/:projectId/remove-deployment", handleRemoveDeployment);
1295 projectRouter.get("/", handleProjectAll);
1296 projectRouter.post("/", handleProjectCreate);
gio918780d2025-05-22 08:24:41 +00001297
gio76d8ae62025-05-19 15:21:54 +00001298 app.use("/api/project", projectRouter); // Mount the authenticated router
1299
giod0026612025-05-08 13:00:36 +00001300 app.use("/", express.static("../front/dist"));
gio09fcab52025-05-12 14:05:07 +00001301
gio76d8ae62025-05-19 15:21:54 +00001302 const internalApi = express();
1303 internalApi.use(express.json());
1304 internalApi.post("/api/project/:projectId/workers", handleRegisterWorker);
gioc31bf142025-06-16 07:48:20 +00001305 internalApi.get("/api/project/:projectId/config", handleConfigGet);
gio10ff1342025-07-05 10:22:15 +00001306 internalApi.post("/api/project/:projectId/saved", handleSave);
gioc31bf142025-06-16 07:48:20 +00001307 internalApi.post("/api/project/:projectId/deploy", handleDeploy);
gio007c8572025-07-08 04:27:35 +00001308 internalApi.get("/api/project/:projectId/env", handleInternalEnv);
gioc31bf142025-06-16 07:48:20 +00001309 internalApi.post("/api/validate-config", handleValidateConfig);
gio09fcab52025-05-12 14:05:07 +00001310
giod0026612025-05-08 13:00:36 +00001311 app.listen(env.DODO_PORT_WEB, () => {
gio09fcab52025-05-12 14:05:07 +00001312 console.log("Web server started on port", env.DODO_PORT_WEB);
1313 });
1314
gio76d8ae62025-05-19 15:21:54 +00001315 internalApi.listen(env.DODO_PORT_API, () => {
gio09fcab52025-05-12 14:05:07 +00001316 console.log("Internal API server started on port", env.DODO_PORT_API);
giod0026612025-05-08 13:00:36 +00001317 });
1318}
1319
gio166d9922025-07-07 17:30:21 +00001320function cleanupWorkers() {
1321 const now = Date.now();
1322 projectMonitors.forEach((monitor) => {
1323 monitor.cleanupWorkers(now);
1324 });
1325 setTimeout(cleanupWorkers, 1000);
1326}
1327
1328setTimeout(cleanupWorkers, 1000);
1329
giod0026612025-05-08 13:00:36 +00001330start();