blob: fb77431a1f5e0676ac11224fef2df159bb837ac5 [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";
7import { AppManager } 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";
gio56e9f472025-07-07 03:33:38 +000028import { GraphOrConfigSchema, GraphSchema, GraphConfigOrDraft } 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 {
389 if (p.instanceId == null) {
gioc31bf142025-06-16 07:48:20 +0000390 const deployResponse = await appManager.deploy(cfg);
giod0026612025-05-08 13:00:36 +0000391 await db.project.update({
392 where: {
393 id: projectId,
394 },
395 data: {
gio56e9f472025-07-07 03:33:38 +0000396 state: JSON.stringify(graph),
giod0026612025-05-08 13:00:36 +0000397 draft: null,
gio3ed59592025-05-14 16:51:09 +0000398 instanceId: deployResponse.id,
giob77cb932025-05-19 09:37:14 +0000399 access: JSON.stringify(deployResponse.access),
giod0026612025-05-08 13:00:36 +0000400 },
401 });
gio56e9f472025-07-07 03:33:38 +0000402 diff = { toAdd: extractGithubRepos(JSON.stringify(graph)) };
gio3ed59592025-05-14 16:51:09 +0000403 } else {
gioc31bf142025-06-16 07:48:20 +0000404 const deployResponse = await appManager.update(p.instanceId, cfg);
gio56e9f472025-07-07 03:33:38 +0000405 diff = calculateRepoDiff(extractGithubRepos(p.state), extractGithubRepos(JSON.stringify(graph)));
giob77cb932025-05-19 09:37:14 +0000406 await db.project.update({
407 where: {
408 id: projectId,
409 },
410 data: {
gio56e9f472025-07-07 03:33:38 +0000411 state: JSON.stringify(graph),
giob77cb932025-05-19 09:37:14 +0000412 draft: null,
413 access: JSON.stringify(deployResponse.access),
414 },
415 });
giod0026612025-05-08 13:00:36 +0000416 }
gio3ed59592025-05-14 16:51:09 +0000417 if (diff && p.githubToken && deployKey) {
418 const github = new GithubClient(p.githubToken);
gioa71316d2025-05-24 09:41:36 +0400419 await manageGithubRepos(github, diff, deployKeyPublic!, env.PUBLIC_ADDR);
giod0026612025-05-08 13:00:36 +0000420 }
gio3ed59592025-05-14 16:51:09 +0000421 resp.status(200);
422 } catch (error) {
423 console.error("Deployment error:", error);
424 resp.status(500);
425 resp.write(JSON.stringify({ error: "Deployment failed" }));
giod0026612025-05-08 13:00:36 +0000426 }
427 } catch (e) {
428 console.log(e);
429 resp.status(500);
430 } finally {
431 resp.end();
432 }
433};
434
gio10ff1342025-07-05 10:22:15 +0000435const handleSave: express.Handler = async (req, resp) => {
gio8a5f12f2025-07-05 07:02:31 +0000436 try {
437 const projectId = Number(req.params["projectId"]);
438 const p = await db.project.findUnique({
439 where: {
440 id: projectId,
gio10ff1342025-07-05 10:22:15 +0000441 userId: resp.locals.userId,
gio8a5f12f2025-07-05 07:02:31 +0000442 },
443 select: {
444 instanceId: true,
445 githubToken: true,
446 deployKey: true,
447 deployKeyPublic: true,
448 state: true,
449 geminiApiKey: true,
450 anthropicApiKey: true,
451 },
452 });
453 if (p === null) {
454 resp.status(404);
455 return;
456 }
gio10ff1342025-07-05 10:22:15 +0000457 const gc = GraphOrConfigSchema.safeParse(req.body);
458 if (!gc.success) {
gio8a5f12f2025-07-05 07:02:31 +0000459 resp.status(400);
gio10ff1342025-07-05 10:22:15 +0000460 resp.write(JSON.stringify({ error: "Invalid configuration", issues: gc.error.format() }));
461 return;
462 }
463 if (gc.data.type === "graph") {
464 await db.project.update({
465 where: { id: projectId },
466 data: { draft: JSON.stringify(gc.data.graph) },
467 });
468 resp.status(200);
gio8a5f12f2025-07-05 07:02:31 +0000469 return;
470 }
471 let repos: GithubRepository[] = [];
472 if (p.githubToken) {
473 const github = new GithubClient(p.githubToken);
474 repos = await github.getRepositories();
475 }
476 const state = JSON.stringify(
477 configToGraph(
gio10ff1342025-07-05 10:22:15 +0000478 gc.data.config,
gio8a5f12f2025-07-05 07:02:31 +0000479 getNetworks(resp.locals.username),
480 repos,
gio10ff1342025-07-05 10:22:15 +0000481 p.state ? parseGraph(p.state)!.data! : undefined,
gio8a5f12f2025-07-05 07:02:31 +0000482 ),
483 );
484 await db.project.update({
485 where: { id: projectId },
486 data: { draft: state },
487 });
488 resp.status(200);
489 } catch (e) {
490 console.log(e);
491 resp.status(500);
492 } finally {
493 resp.end();
494 }
495};
496
giod0026612025-05-08 13:00:36 +0000497const handleStatus: express.Handler = async (req, resp) => {
498 try {
499 const projectId = Number(req.params["projectId"]);
500 const p = await db.project.findUnique({
501 where: {
502 id: projectId,
gio09fcab52025-05-12 14:05:07 +0000503 userId: resp.locals.userId,
giod0026612025-05-08 13:00:36 +0000504 },
505 select: {
506 instanceId: true,
507 },
508 });
giod0026612025-05-08 13:00:36 +0000509 if (p === null) {
510 resp.status(404);
511 return;
512 }
513 if (p.instanceId == null) {
514 resp.status(404);
515 return;
516 }
gio3ed59592025-05-14 16:51:09 +0000517 try {
518 const status = await appManager.getStatus(p.instanceId);
519 resp.status(200);
520 resp.write(JSON.stringify(status));
521 } catch (error) {
522 console.error("Error getting status:", error);
523 resp.status(500);
giod0026612025-05-08 13:00:36 +0000524 }
525 } catch (e) {
526 console.log(e);
527 resp.status(500);
528 } finally {
529 resp.end();
530 }
531};
532
gioc31bf142025-06-16 07:48:20 +0000533const handleConfigGet: express.Handler = async (req, resp) => {
534 try {
535 const projectId = Number(req.params["projectId"]);
536 const project = await db.project.findUnique({
537 where: {
538 id: projectId,
539 },
540 select: {
541 state: true,
542 },
543 });
544
545 if (!project || !project.state) {
546 resp.status(404).send({ error: "No deployed configuration found." });
547 return;
548 }
549
gio10ff1342025-07-05 10:22:15 +0000550 const state = parseGraph(project.state)!.data!;
gioc31bf142025-06-16 07:48:20 +0000551 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
552 const config = generateDodoConfig(projectId.toString(), state.nodes, env);
553
554 if (!config) {
555 resp.status(500).send({ error: "Failed to generate configuration." });
556 return;
557 }
558 resp.status(200).json(config);
559 } catch (e) {
560 console.log(e);
561 resp.status(500).send({ error: "Internal server error" });
562 } finally {
563 console.log("config get done");
564 resp.end();
565 }
566};
567
giobd37a2b2025-05-15 04:28:42 +0000568const handleRemoveDeployment: express.Handler = async (req, resp) => {
569 try {
570 const projectId = Number(req.params["projectId"]);
571 const p = await db.project.findUnique({
572 where: {
573 id: projectId,
574 userId: resp.locals.userId,
575 },
576 select: {
577 instanceId: true,
578 githubToken: true,
gioa71316d2025-05-24 09:41:36 +0400579 deployKeyPublic: true,
giobd37a2b2025-05-15 04:28:42 +0000580 state: true,
581 draft: true,
582 },
583 });
584 if (p === null) {
585 resp.status(404);
586 resp.write(JSON.stringify({ error: "Project not found" }));
587 return;
588 }
589 if (p.instanceId == null) {
590 resp.status(400);
591 resp.write(JSON.stringify({ error: "Project not deployed" }));
592 return;
593 }
594 const removed = await appManager.removeInstance(p.instanceId);
595 if (!removed) {
596 resp.status(500);
597 resp.write(JSON.stringify({ error: "Failed to remove deployment from cluster" }));
598 return;
599 }
gioa71316d2025-05-24 09:41:36 +0400600 if (p.githubToken && p.deployKeyPublic && p.state) {
giobd37a2b2025-05-15 04:28:42 +0000601 try {
602 const github = new GithubClient(p.githubToken);
603 const repos = extractGithubRepos(p.state);
604 const diff = { toDelete: repos, toAdd: [] };
gioa71316d2025-05-24 09:41:36 +0400605 await manageGithubRepos(github, diff, p.deployKeyPublic, env.PUBLIC_ADDR);
giobd37a2b2025-05-15 04:28:42 +0000606 } catch (error) {
607 console.error("Error removing GitHub deploy keys:", error);
608 }
609 }
610 await db.project.update({
611 where: {
612 id: projectId,
613 },
614 data: {
615 instanceId: null,
gioa71316d2025-05-24 09:41:36 +0400616 deployKeyPublic: null,
giob77cb932025-05-19 09:37:14 +0000617 access: null,
giobd37a2b2025-05-15 04:28:42 +0000618 state: null,
619 draft: p.draft ?? p.state,
620 },
621 });
622 resp.status(200);
623 resp.write(JSON.stringify({ success: true }));
624 } catch (e) {
625 console.error("Error removing deployment:", e);
626 resp.status(500);
627 resp.write(JSON.stringify({ error: "Internal server error" }));
628 } finally {
629 resp.end();
630 }
631};
632
giod0026612025-05-08 13:00:36 +0000633const handleGithubRepos: express.Handler = async (req, resp) => {
634 try {
635 const projectId = Number(req.params["projectId"]);
636 const project = await db.project.findUnique({
gio09fcab52025-05-12 14:05:07 +0000637 where: {
638 id: projectId,
639 userId: resp.locals.userId,
640 },
641 select: {
642 githubToken: true,
643 },
giod0026612025-05-08 13:00:36 +0000644 });
giod0026612025-05-08 13:00:36 +0000645 if (!project?.githubToken) {
646 resp.status(400);
647 resp.write(JSON.stringify({ error: "GitHub token not configured" }));
648 return;
649 }
giod0026612025-05-08 13:00:36 +0000650 const github = new GithubClient(project.githubToken);
651 const repositories = await github.getRepositories();
giod0026612025-05-08 13:00:36 +0000652 resp.status(200);
653 resp.header("Content-Type", "application/json");
654 resp.write(JSON.stringify(repositories));
655 } catch (e) {
656 console.log(e);
657 resp.status(500);
658 resp.write(JSON.stringify({ error: "Failed to fetch repositories" }));
659 } finally {
660 resp.end();
661 }
662};
663
664const handleUpdateGithubToken: express.Handler = async (req, resp) => {
665 try {
giod0026612025-05-08 13:00:36 +0000666 await db.project.update({
gio09fcab52025-05-12 14:05:07 +0000667 where: {
gio69148322025-06-19 23:16:12 +0400668 id: Number(req.params["projectId"]),
gio09fcab52025-05-12 14:05:07 +0000669 userId: resp.locals.userId,
670 },
gio69148322025-06-19 23:16:12 +0400671 data: {
672 githubToken: req.body.githubToken,
673 },
674 });
675 resp.status(200);
676 } catch (e) {
677 console.log(e);
678 resp.status(500);
679 } finally {
680 resp.end();
681 }
682};
683
684const handleUpdateGeminiToken: express.Handler = async (req, resp) => {
685 try {
686 await db.project.update({
687 where: {
688 id: Number(req.params["projectId"]),
689 userId: resp.locals.userId,
690 },
691 data: {
692 geminiApiKey: req.body.geminiApiKey,
693 },
giod0026612025-05-08 13:00:36 +0000694 });
giod0026612025-05-08 13:00:36 +0000695 resp.status(200);
696 } catch (e) {
697 console.log(e);
698 resp.status(500);
699 } finally {
700 resp.end();
701 }
702};
703
gio69ff7592025-07-03 06:27:21 +0000704const handleUpdateAnthropicToken: express.Handler = async (req, resp) => {
705 try {
706 await db.project.update({
707 where: {
708 id: Number(req.params["projectId"]),
709 userId: resp.locals.userId,
710 },
711 data: {
712 anthropicApiKey: req.body.anthropicApiKey,
713 },
714 });
715 resp.status(200);
716 } catch (e) {
717 console.log(e);
718 resp.status(500);
719 } finally {
720 resp.end();
721 }
722};
723
gioc31bf142025-06-16 07:48:20 +0000724const getNetworks = (username?: string | undefined): Network[] => {
725 return [
726 {
727 name: "Trial",
728 domain: "trial.dodoapp.xyz",
729 hasAuth: false,
730 },
731 // TODO(gio): Remove
732 ].concat(
733 username === "gio" || 1 == 1
734 ? [
735 {
736 name: "Public",
737 domain: "v1.dodo.cloud",
738 hasAuth: true,
739 },
740 {
741 name: "Private",
742 domain: "p.v1.dodo.cloud",
743 hasAuth: true,
744 },
745 ]
746 : [],
747 );
748};
749
750const getEnv = async (projectId: number, userId: string, username: string): Promise<Env> => {
751 const project = await db.project.findUnique({
752 where: {
753 id: projectId,
754 userId,
755 },
756 select: {
757 deployKeyPublic: true,
758 githubToken: true,
gio69148322025-06-19 23:16:12 +0400759 geminiApiKey: true,
gio69ff7592025-07-03 06:27:21 +0000760 anthropicApiKey: true,
gioc31bf142025-06-16 07:48:20 +0000761 access: true,
762 instanceId: true,
763 },
764 });
765 if (!project) {
766 throw new Error("Project not found");
767 }
768 const monitor = projectMonitors.get(projectId);
769 const serviceNames = monitor ? monitor.getAllServiceNames() : [];
770 const services = serviceNames.map((name: string) => ({
771 name,
772 workers: [...(monitor ? monitor.getWorkerStatusesForService(name) : new Map()).entries()].map(
773 ([id, status]) => ({
774 ...status,
775 id,
776 }),
777 ),
778 }));
779 return {
gioc31bf142025-06-16 07:48:20 +0000780 deployKeyPublic: project.deployKeyPublic == null ? undefined : project.deployKeyPublic,
781 instanceId: project.instanceId == null ? undefined : project.instanceId,
782 access: JSON.parse(project.access ?? "[]"),
783 integrations: {
784 github: !!project.githubToken,
gio69148322025-06-19 23:16:12 +0400785 gemini: !!project.geminiApiKey,
gio69ff7592025-07-03 06:27:21 +0000786 anthropic: !!project.anthropicApiKey,
gioc31bf142025-06-16 07:48:20 +0000787 },
788 networks: getNetworks(username),
789 services,
790 user: {
791 id: userId,
792 username: username,
793 },
794 };
795};
796
giod0026612025-05-08 13:00:36 +0000797const handleEnv: express.Handler = async (req, resp) => {
798 const projectId = Number(req.params["projectId"]);
799 try {
gioc31bf142025-06-16 07:48:20 +0000800 const env = await getEnv(projectId, resp.locals.userId, resp.locals.username);
giod0026612025-05-08 13:00:36 +0000801 resp.status(200);
gioc31bf142025-06-16 07:48:20 +0000802 resp.write(JSON.stringify(env));
giod0026612025-05-08 13:00:36 +0000803 } catch (error) {
gioc31bf142025-06-16 07:48:20 +0000804 console.error("Error getting env:", error);
giod0026612025-05-08 13:00:36 +0000805 resp.status(500);
806 resp.write(JSON.stringify({ error: "Internal server error" }));
807 } finally {
808 resp.end();
809 }
810};
811
gio3a921b82025-05-10 07:36:09 +0000812const handleServiceLogs: express.Handler = async (req, resp) => {
gio78a22882025-07-01 18:56:01 +0000813 const projectId = Number(req.params["projectId"]);
814 const service = req.params["service"];
815 const workerId = req.params["workerId"];
816
817 resp.setHeader("Content-Type", "text/event-stream");
818 resp.setHeader("Cache-Control", "no-cache");
819 resp.setHeader("Connection", "keep-alive");
820 resp.flushHeaders();
821
822 const timestampFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
823 const sendLogs = (logs: LogItem[]) => {
824 if (logs.length == 0) {
825 return;
826 }
827 const logString = logs
828 .map((l) => {
829 const t = Instant.ofEpochMilli(l.timestampMilli);
830 const formattedTimestamp = t.atZone(ZoneId.UTC).format(timestampFormat);
831 return `\x1b[38;5;240m${formattedTimestamp}\x1b[0m ${l.contents}`;
832 })
833 .join("\n");
834 resp.write("event: message\n");
835 resp.write(`data: ${JSON.stringify({ logs: logString })}\n\n`);
836 };
837
gio3a921b82025-05-10 07:36:09 +0000838 try {
gio09fcab52025-05-12 14:05:07 +0000839 const project = await db.project.findUnique({
gio78a22882025-07-01 18:56:01 +0000840 where: { id: projectId, userId: resp.locals.userId },
gio09fcab52025-05-12 14:05:07 +0000841 });
gio78a22882025-07-01 18:56:01 +0000842
843 if (!project) {
844 resp.status(404).end();
gio09fcab52025-05-12 14:05:07 +0000845 return;
846 }
gio78a22882025-07-01 18:56:01 +0000847
gioa1efbad2025-05-21 07:16:45 +0000848 const monitor = projectMonitors.get(projectId);
gio78a22882025-07-01 18:56:01 +0000849 if (!monitor) {
850 resp.status(404).end();
gio3a921b82025-05-10 07:36:09 +0000851 return;
852 }
gio78a22882025-07-01 18:56:01 +0000853
gio40c0c992025-07-02 13:18:05 +0000854 let lastLogId: number | undefined = undefined;
855 const initialLogs = (await logStore.get(projectId, service, workerId)) || [];
gio8a5f12f2025-07-05 07:02:31 +0000856 await sendLogs(initialLogs);
gio40c0c992025-07-02 13:18:05 +0000857 if (initialLogs.length > 0) {
858 lastLogId = initialLogs[initialLogs.length - 1].id;
859 }
gio78a22882025-07-01 18:56:01 +0000860 resp.flushHeaders();
861
gio40c0c992025-07-02 13:18:05 +0000862 const intervalId = setInterval(async () => {
863 const currentLogs = (await logStore.get(projectId, service, workerId, lastLogId)) || [];
864 if (currentLogs.length > 0) {
gio8a5f12f2025-07-05 07:02:31 +0000865 await sendLogs(currentLogs);
gio40c0c992025-07-02 13:18:05 +0000866 lastLogId = currentLogs[currentLogs.length - 1].id;
gio78a22882025-07-01 18:56:01 +0000867 }
868 }, 500);
869
870 req.on("close", () => {
871 clearInterval(intervalId);
872 resp.end();
873 });
gio3a921b82025-05-10 07:36:09 +0000874 } catch (e) {
875 console.log(e);
gio78a22882025-07-01 18:56:01 +0000876 resp.status(500).end();
gio3a921b82025-05-10 07:36:09 +0000877 }
878};
879
gio7d813702025-05-08 18:29:52 +0000880const handleRegisterWorker: express.Handler = async (req, resp) => {
881 try {
882 const projectId = Number(req.params["projectId"]);
gio7d813702025-05-08 18:29:52 +0000883 const result = WorkerSchema.safeParse(req.body);
gio7d813702025-05-08 18:29:52 +0000884 if (!result.success) {
gioa70535a2025-07-02 15:50:25 +0000885 console.log(JSON.stringify(result.error));
gio7d813702025-05-08 18:29:52 +0000886 resp.status(400);
887 resp.write(
888 JSON.stringify({
889 error: "Invalid request data",
890 details: result.error.format(),
891 }),
892 );
893 return;
894 }
gioa1efbad2025-05-21 07:16:45 +0000895 let monitor = projectMonitors.get(projectId);
896 if (!monitor) {
897 monitor = new ProjectMonitor();
898 projectMonitors.set(projectId, monitor);
gio7d813702025-05-08 18:29:52 +0000899 }
gioa1efbad2025-05-21 07:16:45 +0000900 monitor.registerWorker(result.data);
gio40c0c992025-07-02 13:18:05 +0000901 if (result.data.logs) {
902 await logStore.store(projectId, result.data.service, result.data.id, result.data.logs);
903 }
gio7d813702025-05-08 18:29:52 +0000904 resp.status(200);
905 resp.write(
906 JSON.stringify({
907 success: true,
gio78a22882025-07-01 18:56:01 +0000908 logItemsConsumed: result.data.logs?.length ?? 0,
gio7d813702025-05-08 18:29:52 +0000909 }),
910 );
911 } catch (e) {
912 console.log(e);
913 resp.status(500);
914 resp.write(JSON.stringify({ error: "Failed to register worker" }));
915 } finally {
916 resp.end();
917 }
918};
919
gio76d8ae62025-05-19 15:21:54 +0000920async function reloadProject(projectId: number): Promise<boolean> {
gioa1efbad2025-05-21 07:16:45 +0000921 const monitor = projectMonitors.get(projectId);
922 const projectWorkers = monitor ? monitor.getWorkerAddresses() : [];
gio76d8ae62025-05-19 15:21:54 +0000923 const workerCount = projectWorkers.length;
924 if (workerCount === 0) {
925 return true;
926 }
927 const results = await Promise.all(
gioc31bf142025-06-16 07:48:20 +0000928 projectWorkers.map(async (workerAddress: string) => {
929 try {
930 const { data } = await axios.get(`http://${workerAddress}/reload`);
931 return data.every((s: { status: string }) => s.status === "ok");
932 } catch (error) {
933 console.error(`Failed to reload worker ${workerAddress}:`, error);
934 return false;
935 }
gio76d8ae62025-05-19 15:21:54 +0000936 }),
937 );
gioc31bf142025-06-16 07:48:20 +0000938 return results.reduce((acc: boolean, curr: boolean) => acc && curr, true);
gio76d8ae62025-05-19 15:21:54 +0000939}
940
gio7d813702025-05-08 18:29:52 +0000941const handleReload: express.Handler = async (req, resp) => {
942 try {
943 const projectId = Number(req.params["projectId"]);
gio76d8ae62025-05-19 15:21:54 +0000944 const projectAuth = await db.project.findFirst({
gio09fcab52025-05-12 14:05:07 +0000945 where: {
946 id: projectId,
947 userId: resp.locals.userId,
948 },
gio76d8ae62025-05-19 15:21:54 +0000949 select: { id: true },
gio09fcab52025-05-12 14:05:07 +0000950 });
gio76d8ae62025-05-19 15:21:54 +0000951 if (!projectAuth) {
gio09fcab52025-05-12 14:05:07 +0000952 resp.status(404);
gio09fcab52025-05-12 14:05:07 +0000953 return;
954 }
gio76d8ae62025-05-19 15:21:54 +0000955 const success = await reloadProject(projectId);
956 if (success) {
957 resp.status(200);
958 } else {
959 resp.status(500);
gio7d813702025-05-08 18:29:52 +0000960 }
gio7d813702025-05-08 18:29:52 +0000961 } catch (e) {
gio76d8ae62025-05-19 15:21:54 +0000962 console.error(e);
gio7d813702025-05-08 18:29:52 +0000963 resp.status(500);
gio7d813702025-05-08 18:29:52 +0000964 }
965};
966
gio577d2342025-07-03 12:50:18 +0000967const handleQuitWorker: express.Handler = async (req, resp) => {
968 const projectId = Number(req.params["projectId"]);
969 const serviceName = req.params["serviceName"];
970 const workerId = req.params["workerId"];
971
972 const projectMonitor = projectMonitors.get(projectId);
973 if (!projectMonitor) {
974 resp.status(404).send({ error: "Project monitor not found" });
975 return;
976 }
977
978 try {
979 await projectMonitor.terminateWorker(serviceName, workerId);
980 resp.status(200).send({ message: "Worker termination initiated" });
981 } catch (error) {
982 console.error(
983 `Failed to terminate worker ${workerId} in service ${serviceName} for project ${projectId}:`,
984 error,
985 );
986 const errorMessage = error instanceof Error ? error.message : "Unknown error";
987 resp.status(500).send({ error: `Failed to terminate worker: ${errorMessage}` });
988 }
989};
990
gio918780d2025-05-22 08:24:41 +0000991const handleReloadWorker: express.Handler = async (req, resp) => {
992 const projectId = Number(req.params["projectId"]);
993 const serviceName = req.params["serviceName"];
994 const workerId = req.params["workerId"];
995
996 const projectMonitor = projectMonitors.get(projectId);
997 if (!projectMonitor) {
998 resp.status(404).send({ error: "Project monitor not found" });
999 return;
1000 }
1001
1002 try {
1003 await projectMonitor.reloadWorker(serviceName, workerId);
1004 resp.status(200).send({ message: "Worker reload initiated" });
1005 } catch (error) {
1006 console.error(`Failed to reload worker ${workerId} in service ${serviceName} for project ${projectId}:`, error);
1007 const errorMessage = error instanceof Error ? error.message : "Unknown error";
1008 resp.status(500).send({ error: `Failed to reload worker: ${errorMessage}` });
1009 }
1010};
1011
gioa71316d2025-05-24 09:41:36 +04001012const analyzeRepoReqSchema = z.object({
1013 address: z.string(),
1014});
1015
1016const handleAnalyzeRepo: express.Handler = async (req, resp) => {
1017 const projectId = Number(req.params["projectId"]);
1018 const project = await db.project.findUnique({
1019 where: {
1020 id: projectId,
1021 userId: resp.locals.userId,
1022 },
1023 select: {
1024 githubToken: true,
1025 deployKey: true,
1026 deployKeyPublic: true,
1027 },
1028 });
1029 if (!project) {
1030 resp.status(404).send({ error: "Project not found" });
1031 return;
1032 }
1033 if (!project.githubToken) {
1034 resp.status(400).send({ error: "GitHub token not configured" });
1035 return;
1036 }
gio8e74dc02025-06-13 10:19:26 +00001037 let tmpDir: tmp.DirResult | null = null;
1038 try {
1039 let deployKey: string | null = project.deployKey;
1040 let deployKeyPublic: string | null = project.deployKeyPublic;
1041 if (!deployKeyPublic) {
1042 [deployKeyPublic, deployKey] = await generateKey(tmp.dirSync().name);
1043 await db.project.update({
1044 where: { id: projectId },
1045 data: {
1046 deployKeyPublic: deployKeyPublic,
1047 deployKey: deployKey,
1048 },
1049 });
1050 }
1051 const github = new GithubClient(project.githubToken);
1052 const result = analyzeRepoReqSchema.safeParse(req.body);
1053 if (!result.success) {
1054 resp.status(400).send({ error: "Invalid request data" });
1055 return;
1056 }
1057 const { address } = result.data;
1058 tmpDir = tmp.dirSync({
1059 unsafeCleanup: true,
gioa71316d2025-05-24 09:41:36 +04001060 });
gio8e74dc02025-06-13 10:19:26 +00001061 await github.addDeployKey(address, deployKeyPublic);
1062 await fs.promises.writeFile(path.join(tmpDir.name, "key"), deployKey!, {
1063 mode: 0o600,
1064 });
1065 shell.exec(
1066 `GIT_SSH_COMMAND='ssh -i ${tmpDir.name}/key -o IdentitiesOnly=yes' git clone ${address} ${tmpDir.name}/code`,
1067 );
1068 const fsc = new RealFileSystem(`${tmpDir.name}/code`);
1069 const analyzer = new NodeJSAnalyzer();
1070 const info = await analyzer.analyze(fsc, "/");
1071 resp.status(200).send([info]);
1072 } catch (e) {
1073 console.error(e);
1074 resp.status(500).send({ error: "Failed to analyze repository" });
1075 } finally {
1076 if (tmpDir) {
1077 tmpDir.removeCallback();
1078 }
1079 resp.end();
gioa71316d2025-05-24 09:41:36 +04001080 }
gioa71316d2025-05-24 09:41:36 +04001081};
1082
gio09fcab52025-05-12 14:05:07 +00001083const auth = (req: express.Request, resp: express.Response, next: express.NextFunction) => {
gio69148322025-06-19 23:16:12 +04001084 // Hardcoded user for development
1085 resp.locals.userId = "1";
1086 resp.locals.username = "gio";
gio09fcab52025-05-12 14:05:07 +00001087 next();
1088};
1089
gio76d8ae62025-05-19 15:21:54 +00001090const handleGithubPushWebhook: express.Handler = async (req, resp) => {
1091 try {
1092 // TODO(gio): Implement GitHub signature verification for security
1093 const webhookSchema = z.object({
1094 repository: z.object({
1095 ssh_url: z.string(),
1096 }),
1097 });
1098
1099 const result = webhookSchema.safeParse(req.body);
1100 if (!result.success) {
1101 console.warn("GitHub webhook: Invalid payload:", result.error.issues);
1102 resp.status(400).json({ error: "Invalid webhook payload" });
1103 return;
1104 }
1105 const { ssh_url: addr } = result.data.repository;
1106 const allProjects = await db.project.findMany({
1107 select: {
1108 id: true,
1109 state: true,
1110 },
1111 where: {
1112 instanceId: {
1113 not: null,
1114 },
1115 },
1116 });
1117 // TODO(gio): This should run in background
1118 new Promise<boolean>((resolve, reject) => {
1119 setTimeout(() => {
1120 const projectsToReloadIds: number[] = [];
1121 for (const project of allProjects) {
1122 if (project.state && project.state.length > 0) {
1123 const projectRepos = extractGithubRepos(project.state);
1124 if (projectRepos.includes(addr)) {
1125 projectsToReloadIds.push(project.id);
1126 }
1127 }
1128 }
1129 Promise.all(projectsToReloadIds.map((id) => reloadProject(id)))
1130 .then((results) => {
1131 resolve(results.reduce((acc, curr) => acc && curr, true));
1132 })
1133 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1134 .catch((reason: any) => reject(reason));
1135 }, 10);
1136 });
1137 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1138 } catch (error: any) {
1139 console.error(error);
1140 resp.status(500);
1141 }
1142};
1143
gioc31bf142025-06-16 07:48:20 +00001144const handleValidateConfig: express.Handler = async (req, resp) => {
1145 try {
1146 const validationResult = ConfigSchema.safeParse(req.body);
1147 if (!validationResult.success) {
1148 resp.status(400);
1149 resp.header("Content-Type", "application/json");
1150 resp.write(JSON.stringify({ success: false, errors: validationResult.error.flatten() }));
1151 } else {
1152 resp.status(200);
1153 resp.header("Content-Type", "application/json");
1154 resp.write(JSON.stringify({ success: true }));
1155 }
1156 } catch (e) {
1157 console.log(e);
1158 resp.status(500);
1159 } finally {
1160 resp.end();
1161 }
1162};
1163
gio8a5f12f2025-07-05 07:02:31 +00001164function handleStateGetStream(state: "deploy" | "draft"): express.Handler {
1165 return async (req, resp) => {
1166 resp.setHeader("Content-Type", "text/event-stream");
1167 resp.setHeader("Cache-Control", "no-cache");
1168 resp.setHeader("Connection", "keep-alive");
1169 resp.flushHeaders();
1170
1171 try {
1172 let intervalId: NodeJS.Timeout | null = null;
1173 let lastState: Graph | null = null;
1174 const sendState = async () => {
1175 const currentState = await getState(Number(req.params["projectId"]), resp.locals.userId, state);
1176 if (currentState == null) {
1177 resp.status(404).end();
1178 return;
1179 }
1180 if (JSON.stringify(currentState) !== JSON.stringify(lastState)) {
1181 lastState = currentState;
1182 resp.write("event: message\n");
1183 resp.write(`data: ${JSON.stringify(currentState)}\n\n`);
1184 }
1185 intervalId = setTimeout(sendState, 500);
1186 };
1187
1188 await sendState();
1189
1190 req.on("close", () => {
1191 if (intervalId) {
1192 clearTimeout(intervalId);
1193 }
1194 resp.end();
1195 });
1196 } catch (e) {
1197 console.log(e);
1198 resp.end();
1199 }
1200 };
1201}
1202
giod0026612025-05-08 13:00:36 +00001203async function start() {
1204 await db.$connect();
1205 const app = express();
gioc31bf142025-06-16 07:48:20 +00001206 app.set("json spaces", 2);
gio76d8ae62025-05-19 15:21:54 +00001207 app.use(express.json()); // Global JSON parsing
1208
1209 // Public webhook route - no auth needed
1210 app.post("/api/webhook/github/push", handleGithubPushWebhook);
1211
1212 // Authenticated project routes
1213 const projectRouter = express.Router();
gioa71316d2025-05-24 09:41:36 +04001214 projectRouter.use(auth);
1215 projectRouter.post("/:projectId/analyze", handleAnalyzeRepo);
gio76d8ae62025-05-19 15:21:54 +00001216 projectRouter.post("/:projectId/saved", handleSave);
gio8a5f12f2025-07-05 07:02:31 +00001217 projectRouter.get("/:projectId/state/stream/deploy", handleStateGetStream("deploy"));
1218 projectRouter.get("/:projectId/state/stream/draft", handleStateGetStream("draft"));
gio76d8ae62025-05-19 15:21:54 +00001219 projectRouter.get("/:projectId/saved/deploy", handleSavedGet("deploy"));
1220 projectRouter.get("/:projectId/saved/draft", handleSavedGet("draft"));
1221 projectRouter.post("/:projectId/deploy", handleDeploy);
1222 projectRouter.get("/:projectId/status", handleStatus);
gioc31bf142025-06-16 07:48:20 +00001223 projectRouter.get("/:projectId/config", handleConfigGet);
gioa71316d2025-05-24 09:41:36 +04001224 projectRouter.delete("/:projectId", handleProjectDelete);
gio76d8ae62025-05-19 15:21:54 +00001225 projectRouter.get("/:projectId/repos/github", handleGithubRepos);
1226 projectRouter.post("/:projectId/github-token", handleUpdateGithubToken);
gio69148322025-06-19 23:16:12 +04001227 projectRouter.post("/:projectId/gemini-token", handleUpdateGeminiToken);
gio69ff7592025-07-03 06:27:21 +00001228 projectRouter.post("/:projectId/anthropic-token", handleUpdateAnthropicToken);
gio76d8ae62025-05-19 15:21:54 +00001229 projectRouter.get("/:projectId/env", handleEnv);
gio918780d2025-05-22 08:24:41 +00001230 projectRouter.post("/:projectId/reload/:serviceName/:workerId", handleReloadWorker);
gio577d2342025-07-03 12:50:18 +00001231 projectRouter.post("/:projectId/quitquitquit/:serviceName/:workerId", handleQuitWorker);
gio76d8ae62025-05-19 15:21:54 +00001232 projectRouter.post("/:projectId/reload", handleReload);
gioa1efbad2025-05-21 07:16:45 +00001233 projectRouter.get("/:projectId/logs/:service/:workerId", handleServiceLogs);
gio76d8ae62025-05-19 15:21:54 +00001234 projectRouter.post("/:projectId/remove-deployment", handleRemoveDeployment);
1235 projectRouter.get("/", handleProjectAll);
1236 projectRouter.post("/", handleProjectCreate);
gio918780d2025-05-22 08:24:41 +00001237
gio76d8ae62025-05-19 15:21:54 +00001238 app.use("/api/project", projectRouter); // Mount the authenticated router
1239
giod0026612025-05-08 13:00:36 +00001240 app.use("/", express.static("../front/dist"));
gio09fcab52025-05-12 14:05:07 +00001241
gio76d8ae62025-05-19 15:21:54 +00001242 const internalApi = express();
1243 internalApi.use(express.json());
1244 internalApi.post("/api/project/:projectId/workers", handleRegisterWorker);
gioc31bf142025-06-16 07:48:20 +00001245 internalApi.get("/api/project/:projectId/config", handleConfigGet);
gio10ff1342025-07-05 10:22:15 +00001246 internalApi.post("/api/project/:projectId/saved", handleSave);
gioc31bf142025-06-16 07:48:20 +00001247 internalApi.post("/api/project/:projectId/deploy", handleDeploy);
1248 internalApi.post("/api/validate-config", handleValidateConfig);
gio09fcab52025-05-12 14:05:07 +00001249
giod0026612025-05-08 13:00:36 +00001250 app.listen(env.DODO_PORT_WEB, () => {
gio09fcab52025-05-12 14:05:07 +00001251 console.log("Web server started on port", env.DODO_PORT_WEB);
1252 });
1253
gio76d8ae62025-05-19 15:21:54 +00001254 internalApi.listen(env.DODO_PORT_API, () => {
gio09fcab52025-05-12 14:05:07 +00001255 console.log("Internal API server started on port", env.DODO_PORT_API);
giod0026612025-05-08 13:00:36 +00001256 });
1257}
1258
1259start();